Reputation: 13
I am trying to show a legend to accompany a plot created using ggplot and geom_col - my legend isn't showing up. I originally plotted these data using geom_bar (with a visible legend but some other problems), but after more research it seems more appropriate to use geom_col.
I know this topic has a ton of google-able questions and answers, but after many searches and code variations I still have no success.
How can I make my legend visible?
My reproducible code is below.
site <- c(0.700, 0.854)
site <- lapply(site, function(x) round((x*100),1))
site <- unlist(site, use.names=FALSE)
state <- c(0.726, 0.808)
state <- lapply(state, function(x) round((x*100),1))
state <- unlist(state, use.names=FALSE)
measure <- c("Individual", "Coalition")
measure <- unlist(measure, use.names=FALSE)
df1 <- data.frame(site,state,measure)
df2 <- melt(df1, id.vars='measure')
df2$variable <- factor(df2$variable,
levels = c('state','site'),ordered = TRUE)
fillcolors <- c("#7189A6", "#817BB0", "#7189A6", "#817BB0")
myplot <-
ggplot(df2, aes(measure, value, group = variable)) +
geom_col(width=.75, position=position_dodge(width=0.80), fill=fillcolors) +
labs(title = paste0("Knowledge & Skills Gained", paste0(rep("", 0), collapse = " ")),
x = "", y = "", fill="") +
scale_y_continuous(limits=c(0,100), labels = function(x){ paste0(x, "%") }) +
coord_flip() +
geom_text(aes(label=(paste0(value,"%"))), size=3,
colour = "#57585a",
position=position_dodge(width=0.75), vjust=.3, hjust=-.1) +
theme(legend.position="right", title = element_text(colour = "#57585a"),
legend.text = element_text(colour="#57585a", size = 9))
myplot
This results in the following plot: myplot
Thank you in advance!
Upvotes: 0
Views: 3283
Reputation: 1277
The main issue is that you should use fill=
, not group=
:
ggplot(df2, aes(measure, value, fill = variable)) +
geom_col(width=.75, position=position_dodge(width=0.80)) +
labs(title = paste0("Knowledge & Skills Gained", paste0(rep("", 0), collapse = " ")),
x = "", y = "", fill="") +
scale_y_continuous(limits=c(0,100), labels = function(x){ paste0(x, "%") }) +
coord_flip() +
geom_text(aes(label=(paste0(value,"%"))), size=3,
colour = "#57585a",
position=position_dodge(width=0.75), vjust=.3, hjust=-.1) +
scale_fill_manual(values = c("#817BB0", "#7189A6")) +
guides(fill = guide_legend(reverse=T))
(There are a lot of other ways in which your code could be cleaned up; I focused only on getting the legend to appear.)
Upvotes: 1