简体   繁体   English

如何在两种不同类型的几何图形 ggplot2 之间创建图例

[英]How to create a legend across two different types of geoms ggplot2

I have two different datasets which I'd like to plot in the same ggplot2 plot, using different geoms for each.我有两个不同的数据集,我想在同一个 ggplot2 图中绘制它们,每个数据集使用不同的几何图形。 Ideally I would also like a legend which shows that the point geom corresponds to one type of data and the line geom corresponds to the other, but I cannot figure out how to do this.理想情况下,我还想要一个图例,它表明点几何对应于一种类型的数据,线几何对应于另一种类型,但我不知道如何做到这一点。 An example of what my data basically looks like is below, minus the legend.我的数据基本上看起来像下面的一个例子,减去图例。

require(ggplot2)

set.seed(1)

d1 = data.frame(y_values = rnorm(21), x_values = 1:21, factor_values = as.factor(sample(1:3, 21, replace=T)))
d2 = data.frame(y_values = seq(-1,1,by = .05), x_values = seq(1,21,by = .5))



ggplot() + 
geom_point(data=d1, aes(x=x_values, y=y_values, color=factor_values)) + 
geom_line(data=d2, aes(x = x_values, y=y_values), color="blue")

Maybe is this what you want?也许这就是你想要的? Two legends for each data.每个数据有两个图例。 You can enable linetype in order to create a new legend so that points and lines can be in different places:您可以启用linetype以创建新图例,以便点和线可以位于不同的位置:

#Code
ggplot() + 
  geom_point(data=d1, aes(x=x_values, y=y_values, color=factor_values)) + 
  geom_line(data=d2, aes(x = x_values, y=y_values,linetype='myline'), color="blue")+
  scale_linetype_manual('My line',values='solid')

Output:输出:

在此处输入图片说明

Or you can also try this:或者你也可以试试这个:

#Code 2
ggplot() + 
  geom_point(data=d1, aes(x=x_values, y=y_values, color=factor_values)) + 
  geom_line(data=d2, aes(x = x_values, y=y_values,linetype='myline'), color="blue")+
  scale_linetype_manual('',values='solid')+
  theme(
    legend.spacing = unit(-17,'pt'),
    legend.margin = margin(t=0,b=0,unit='pt'),
    legend.background = element_blank()
  )+guides(linetype=guide_legend(title="New Legend Title"),
         color=guide_legend(title=""))

Output:输出:

在此处输入图片说明

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

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