【问题标题】:ggplot2: Add legend and associated legend title to barplotggplot2:将图例和关联的图例标题添加到条形图
【发布时间】:2017-01-09 20:08:29
【问题描述】:

我有以下从the data-set 'temp' 生成的条形图(数据位于此堆栈溢出页面的底部,也可以通过上面的此链接找到)。

问题

目标是在条形图(上图)的右侧添加一个标题为 Canopy Type 的图例,标签分别表示 Under Canopy 和 Open Canopy 。

我尝试使用另一个 stackoverflow 答案中给出的 scale_colour_manual,但我无法显示图例。

如果有人可以提供帮助,那么在此先感谢

生成条形图的代码是:

假设您要为每个 Under_Open、Topography 单元格绘制 Canopy_Index 的均值,您可以先形成均值:

 df.means <- aggregate(Canopy_Index ~ Under_Open + Topography, df.melt, mean)

然后,使用您问题中的代码绘制 df.means:

  ggplot(df.means, aes(x = Topography, y = Canopy_Index, 
                     fill = factor(Under_Open), group = Under_Open)) +
  geom_bar(stat = "identity", position = "dodge") +
  scale_fill_discrete(name = "Topographical Feature", 
                      breaks = c("Under_tree", "Open_Canopy"),
                      labels = c("Under Canopy", "Open Canopy")) +
  xlab("Topographical Feature") + ylab("Canopy Index") +
  scale_colour_manual("Canopy Type", values = c("red", "blue")) +
  theme(axis.text.x = element_text(angle = 45, hjust = 1), 
        text = element_text(size=14)) + 
  theme(panel.background = element_blank(), 
        panel.grid.major = element_blank(), 
        panel.grid.minor = element_blank(),
        panel.border = element_blank()) + 
  theme(axis.line.x =     element_line(color="black", size = 0.8),
        axis.line.y = element_line(color="black", size = 0.8)) 

【问题讨论】:

  • 在我的机器上运行该代码会显示名为“地形特征”的图例
  • 使用您的代码,我确实得到了一个由 scale_fill_discrete 生成的图例。 scale_colour_manual 无法生成图例,因为 aes 中没有颜色参数。
  • 这很奇怪!运行代码后,图例无法出现。你有什么建议吗?
  • 重启 R 再试一次,也许可以确保你的包是最新的。
  • 您好 Gregor,感谢您的建议。问题出在代码本身,问题已经解决了。

标签: r ggplot2 bar-chart legend


【解决方案1】:

非常感谢“Thales”提供解决此问题的代码

生成带有相关图例的条形图的代码:

     ggplot(df.means, aes(x=Topography, y=Canopy_Index,fill=Under_Open)) +
     geom_bar(stat="identity", position="dodge") +
     scale_fill_discrete(name="Canopy Type",
                breaks=c("Under_tree", "Open_Canopy"),
                labels=c("Under Canopy", "Open Canopy")) +
     xlab("Topographical Feature") + ylab("Canopy Index")

条形图

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-03-05
    • 2018-05-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多