I would like to have a multi-bar chart, horizontal bars, where the legend for the bar-color is in the same order as the bars themselves. I've looked at several articles that have influenced the example here, but I can't make it work.
In this example, it is the "Group" that is in one order in the bars, and the reverse order in the legend.
library(ggplot2)
# create data for tidy format
Category <- c("Category1","Category2","Category3","Category4","Category5","Category1","Category2","Category3","Category4","Category5","Category1","Category2","Category3","Category4","Category5")
GroupTitle <- c("GroupA","GroupA","GroupA","GroupA","GroupA","GroupB","GroupB","GroupB","GroupB","GroupB","GroupC","GroupC","GroupC","GroupC","GroupC")
Valuelst <- list()
for (i in 1:15){
Valuelst[i] <- runif(1, min=0, max=1)
}
Valuelst <- unlist(Valuelst)
# make data frame
d <- data.frame(Category,GroupTitle,Valuelst)
# set factors and orders desired
d$Category <- factor(d$Category, levels = c("Category5","Category4","Category3","Category2","Category1"))
d$GroupTitle <- factor(d$GroupTitle, levels = c("GroupA","GroupB","GroupC"))
# make graph
ggplot(d, aes(x=Category, y=Valuelst, order = -as.numeric(GroupTitle))) + # order= -as.numeric() is one solution that I read
geom_bar(aes(fill=GroupTitle), stat="identity", position="dodge") +
coord_flip() +
scale_fill_manual("Legenda", values = c("GroupC" = "#deebf7", "GroupB" = "#3182bd", "GroupA" = "#9ecae1")) # scale_fill_manual is another I read
I've commented in the code a couple of places where I tried solutions I saw elsewhere. Namely, I've made sure the Groups are a factor, set the order of that factor, used order = -as.numeric(GroupTitle)
, and tried scale_fill_manual
, all with no effect.
Option 1 - Order: C, B and A
To reverse the legend labels you only need to add: guides(fill = guide_legend(reverse = TRUE))
. Keeping the original order of the bars: C, B and A.
ggplot(d, aes(x = Category,
y = Valuelst,
fill = GroupTitle)) +
geom_bar(stat = "identity", position = "dodge") +
coord_flip() +
scale_fill_manual("Legenda",
values = c(
"GroupC" = "#deebf7",
"GroupB" = "#3182bd",
"GroupA" = "#9ecae1"
)) +
guides(fill = guide_legend(reverse = TRUE))
Option 2 - Order: A, B and C
To reverse the order of the bars, we just reorder the levels before plotting.
d$GroupTitle <- factor(d$GroupTitle, levels = c("GroupC","GroupB","GroupA"))
# make graph
ggplot(d, aes(x = Category,
y = Valuelst,
fill = GroupTitle)) +
geom_bar(stat = "identity", position = "dodge") +
coord_flip() +
scale_fill_manual("Legenda",
values = c(
"GroupC" = "#deebf7",
"GroupB" = "#3182bd",
"GroupA" = "#9ecae1"
)) +
guides(fill=guide_legend(reverse=TRUE))