【问题标题】:Combined line & bar geoms: How to generate proper legend?组合线和条形几何:如何生成正确的图例?
【发布时间】:2012-11-27 04:30:44
【问题描述】:

d2 的图例看起来不错;对于d1,我只想在白色/透明背景上显示水平线。

df = data.frame(
  Date = c("2012-11-30", "2012-12-03", "2012-12-04"),
  d1 = c(9, 5, 11),
  d2 = c(4, 6, 3)
)
ggplot(df, aes(Date)) + 
  geom_bar(aes(y = d2, color = "d2"), stat="identity", fill = "red") +
  geom_line(aes(y = d1, group = 1, color = "d1"))  +
  scale_colour_manual("", values=c("d1" = "blue", "d2" = "red")) 

【问题讨论】:

    标签: r ggplot2 bar-chart legend linechart


    【解决方案1】:
    # Bar graph: Notice the placement of fill argument in aes()  
      geom_bar(aes(y=prop.P*100, fill="Seropositive"), stat = "identity",
               position = "dodge", width = 0.5)+
    
    # This line defines the legend for the bar
      scale_fill_manual(name="", values = c("Seropositive"="steelblue3"))+
    
    # Adding errorbar
      geom_errorbar(aes(ymin = ciLow*100, ymax = ciHigh*100), width = 0.2,
                    position = position_dodge(width=0.8))+
    
    # Adding the line to the graph. Used the color argument within aes() to define custom colour
      geom_line(aes(y=mmr1_cov*100, group=1, color="MMR1 Coverage"), size=1)+
    
    # Adding points represent the plotted data
      geom_point(aes(x=age, y=mmr1_cov*100), color="red", size=2)+
    
    # Here adding the legend for the line graph and define the colour
      scale_color_manual(name="", values=c("MMR1 Coverage"="red"))+
    
    # Label the axis
      labs(x="Age (Months)", y="Percentage")+
    
    # Place the legend bottom of the graph
      theme(legend.position = "bottom")
    

    Section of the graph displaying the results

    【讨论】:

      【解决方案2】:

      这不是一个优雅的解决方案,但至少它给出了一些结果。

      我在geom_bar() 中添加了aes(fill="d2") 并删除了fill="red"。然后我为线和条添加了单独的比例。然后在theme() 我从图例条目中删除了灰色背景。

      为了确保图例中的 d1 显示在 scale_colour_manual(" ") 中的 d2 之前,引号之间应该有额外的空格(“更长的”名称)。

      为了将图例键保留在一行中,legend.box="horizontal" 添加到 theme()

        ggplot(df, aes(Date)) + 
          geom_bar(aes(y = d2,fill="d2"), stat="identity") +
          geom_line(aes(y = d1, group = 1, color = "d1")) +
          scale_colour_manual(" ", values=c("d1" = "blue", "d2" = "red"))+
          scale_fill_manual("",values="red")+
          theme(legend.key=element_blank(),
                legend.title=element_blank(),
                legend.box="horizontal")
      

      【讨论】:

      • 不错的解决方案(我认为,如果我们设置fill="d2",我们可能不需要额外的列)!现在有更多的事情要弄清楚:(a)legend.direction="horizontal",如何将图例保持在一行? (b) 如何协调所有项目之间的空白? (c) 图例中的项目如何控制顺序?
      • 添加点 (a) 和 (c) 的解决方案,并使用 fill="d2" 更新代码
      猜你喜欢
      • 1970-01-01
      • 2019-11-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-04-26
      • 2013-06-29
      相关资源
      最近更新 更多