【问题标题】:ggplot geom_col legend not showingggplot geom_col 图例未显示
【发布时间】:2018-01-07 05:02:37
【问题描述】:

我正在尝试显示一个图例来伴随使用 ggplot 和 geom_col 创建的情节 - 我的图例没有出现。我最初使用 geom_bar 绘制这些数据(带有可见的图例,但存在一些其他问题),但经过更多研究后,使用 geom_col 似乎更合适。

我知道这个主题有大量的谷歌问题和答案,但经过多次搜索和代码变化后,我仍然没有成功。

如何使我的图例可见?

我的可重现代码如下。

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

提前谢谢你!

【问题讨论】:

    标签: r plot ggplot2 legend


    【解决方案1】:

    主要问题是你应该使用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))
    

    (还有很多其他方法可以清理您的代码;我只专注于让图例出现。)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-12-27
      • 2021-12-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-10-29
      相关资源
      最近更新 更多