I try to plot a dataset with ggplot2 which is working properly. But now I fail to sort that plot in my desire. Maybe somebody can help?
Right now, the result looks as follows:
The y-axis has some labels that contain a name and a concatenated priority. These labels shall now be sorted twice: first by the priority and second alphabetically – and the corresponding data accordingly. That means: all bold labels shall be on top, followed by the labels with priority 2 and so on; labels with the same priority should be in alphabetical order from top to bottom.
I tried in so many ways but I did not get it to work. So I am asking for some help now :)
Here is the code:
library(dplyr)
library(ggplot2)
names <- c("Example1", "Test1", "Example2", "Test2", "Example3", "Test3", "Example4", "Test4", "SomethingElse", "SomethingElse2", "SomethingElse3")
priorities <- strtoi(c("1", "1", "1", "1", "3", "3", "2", "2", "2", "3", "1"))
categories <- c("Example", "Test", "Example", "Test", "Example", "Test", "Example", "Test", "Other", "Other", "Other")
start_dates <- as.Date(c("2020-07-01", "2020-07-01", "2021-07-01", "2021-10-01", "2021-01-01", "2020-10-01", "2020-10-01", "2021-10-01", "2020-04-01", "2021-07-01", "2021-07-01"))
end_dates <- as.Date(c("2021-12-31", "2021-12-31", "2022-03-31", "2021-12-31", "2021-06-30", "2020-03-31", "2020-12-31", "2022-03-31", "2020-09-30", "2021-12-31", "2021-12-31"))
labels <- paste(names, priorities, sep=' | ')
df_gantt <- data.frame(
label = labels,
start = start_dates,
end = end_dates,
priority = priorities,
category = categories
)
df_gantt$label <- factor(df_gantt$label, levels=names(rev(sort(table(df_gantt$label)))))
df_gantt$priority <- df_gantt$priority[order(df_gantt$label)]
g <- ggplot(df_gantt, aes(x=start, xend=end, y=label, yend=label)) +
geom_segment(size=6, aes(colour=category)) +
scale_color_manual(limits = c("Example", "Test", "Other"),
values = c("Example"="#8ebc8b",
"Test"="#836fff",
"Other"="#dbc585"),
name = "Category") +
theme(plot.background = element_rect(fill="#ededed"),
axis.text = element_text(size=11),
axis.text.y = element_text(face=ifelse(df_gantt$priority == 1, "bold", "plain"))) +
scale_x_date(sec.axis = dup_axis()) +
xlab(NULL) + ylab(NULL)
g
SOLUTION
(Once the question is closed as a duplicate and no answer could be posted anymore, I will edit my question by that answer, so if somebody else is interested, he will find a solution.)
Thanks to @Marco_CH and to the link on a similar question! These code lines do what I want:
df <- df[order(df$priority, df$label, decreasing=TRUE),]
df$label <- factor(df$label, levels=df$label)