简体   繁体   English

如何在r中的ggplot2中绘制第二个图例

[英]How to plot a second legend in ggplot2 in r

I have two datasets I am trying to display on one chart overlaid in ggplot2 under r. 我有两个数据集,我试图在一个图表上显示,覆盖在r下的ggplot2中。 Dataset 1 needs to be displayed as a grouped set of bars (1 group per country - there are a few countries in the dataset). 数据集1需要显示为一组分组的条形图(每个国家/地区一组 - 数据集中有几个国家/地区)。 Dataset 2 needs to be displayed as a set of colored horizontal lines across the bars. 数据集2需要在条形图上显示为一组彩色水平线。 Note the length of the two datasets differ. 请注意,两个数据集的长度不同。 I have some code below that illustrates what I am trying to do (designed by advice from others). 我在下面有一些代码说明了我正在尝试做什么(根据其他人的建议设计)。

library(ggplot2)

chart1_data <- data.frame(year=c("1998","1998","1998","1998","1998","1998","1998","1998","1998"), medicine=c("Fent","Meth","Morph","Fent","Meth","Morph","Fent","Meth","Morph"), entity=c("Italy","Italy","Italy","Norway","Norway","Norway","Portugal","Portugal","Portugal"), usage=c(3.01,9.32,2.01,1.24,1.43,28.48,5.01,5.51,41.82))

chart1_means <- data.frame(label=c("Global Fent","EURO Fent","Global Meth","EURO meth","Global Morph","EURO Morph"), value=c(0.03, 0.07, 1.59, 5.12, 3.28, 8.54))

means_labels = chart1_means$label
colors = rainbow(length(means_labels))

ggplot(data=chart1_data, aes(x=entity, y=usage, fill=medicine)) +
geom_bar(stat="identity", position=position_dodge(), show.legend=TRUE) +
geom_hline(data=chart1_means, aes(yintercept=value), color=colors) +
scale_fill_manual("means", values=colors, guide=guide_legend(override.aes = list(colors)))

The difficulty I'm running into is that I need two legends; 我遇到的困难是我需要两个传说; one for the bars and one for the lines. 一个用于条形,一个用于线条。 All my attempts so far make one legend with pieces of each dataset intermixed to some degree. 到目前为止,我所有的尝试都会产生一个图例,每个数据集的碎片在某种程度上混合在一起。 For example in the chart below notice the single legend with wrong title and nothing about lines. 例如,在下面的图表中,请注意标题错误的单个图例,而没有关于行的图例。

结果情节

Does anyone have a recommendation on how I can accomplish what I want? 有没有人建议如何实现我的目标? Any pointers appreciated. 任何指针赞赏。

As @rawr suggests, things that are mapped use aes() get legends automatically. 正如@rawr建议的那样,映射的东西使用aes()自动获取图例。 So do that. 那样做吧。

ggplot(data = chart1_data, aes(x = entity, y = usage, fill = medicine)) +
    geom_bar(stat = "identity",
             position = position_dodge(),
             show.legend = TRUE) +
    geom_hline(data = chart1_means, aes(yintercept = value, color = label)) +
    scale_fill_manual("means",
                      values = colors) +
    scale_color_manual("lines (means?)",
                       values = colors,
                       guide = guide_legend(override.aes = list(fill = NA)))

在此输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM