我试图展示一个传奇,伴随着使用ggplot和geom_col创建的情节 - 我的传奇没有出现。我最初使用geom_bar绘制这些数据(有一个可见的图例,但有一些其他问题),但经过更多的研究,使用geom_col似乎更合适。
我知道这个话题有很多google-able的问题和答案,但经过多次搜索和代码变化后,我仍然没有成功。
如何让我的传奇可见?
我的可重复代码如下。
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
这导致以下情节:myplot
提前谢谢!
答案 0 :(得分:0)
主要问题是您应该使用fill=
,而不是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))
(还有很多其他方法可以清理你的代码;我只专注于让传奇出现。)