从两个数据帧构建图时的ggplot图例 [英] ggplot legends when plot is built from two data frames

查看:99
本文介绍了从两个数据帧构建图时的ggplot图例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有来自两个不同数据帧的数据.我正在尝试为每个数据框创建图例.我知道我可以组合数据框并执行此操作,但是由于我的数据源,从两个不同的数据框进行绘制最有意义.

I have data coming from two different data frames. I am trying to create legend for each data frame. I know I can combine the data frame and do it, but because of my data source it makes the most sense to plot from two different data frames.

请在下面找到简化的示例.我已经接近了,但传说中的主要预报"只是白色.我想显示主要预测"在外部为红色,内部为白色的位置.

Please find the simplified example below. I have gotten close but the 'Main Forecast' in the legend is only white color. I want to show where 'Main Forecast' is red on the outside and white on the inside.

x = seq(1,10, 1)
y = seq(10,100, 10)

df  = data.frame(x=x, y=y)
df2 = data.frame(x=5, y=50)

p = ggplot(data=df) + 
  geom_point(data=df,aes(x=x, y=y, color="Weekly Forecast"), fill="red", size=5, shape=16)  + 
  geom_line(data=df,aes(x=x, y=y), color="red", size=1)  + 
  geom_point(data=df2, aes(x=x, y=y, color="Main Forecast"), size=2, shape=16)  +
  scale_color_manual("Legend Title", breaks=c("Weekly Forecast", "Main Forecast"), values = c("white","red"))
p

任何帮助将不胜感激.

Any assistance will be greatly appreciated.

推荐答案

您需要使用一个填充符号(pch = 21:25).然后,您需要使用override.aes正确设置图例.我已经将共享数据和aes移到了ggplot命令中.

You need to use one of the symbols that takes a fill (pch = 21:25). You then need to use override.aes to get the legend right. I've moved shared data and aes into the ggplot command.

ggplot(data=df, aes(x=x, y=y)) + 
  geom_point(aes(color="Weekly Forecast"), shape=16, size = 5)  + 
  geom_line(color="red", size=1)  + 
  geom_point(data=df2, aes(color="Main Forecast"), shape=21, fill = "white", size = 5)  +
  scale_color_manual("Legend Title", limits=c("Weekly Forecast", "Main Forecast"), values = c("red","red")) +
  guides(colour = guide_legend(override.aes = list(pch = c(16, 21), fill = c("red", "white"))))

这也可以不用override.aes来完成:

ggplot(data=df, aes(x=x, y=y)) + 
  geom_line(aes(color="Main Forecast"), size=1)  + 
  geom_point(aes(color="Weekly Forecast", fill="Weekly Forecast"), shape=21, size = 5)  +
  geom_point(data=df2, aes(color="Main Forecast", fill="Main Forecast"), shape=21, size = 5)  +
  scale_color_manual(name="", values = c("red","red")) +
  scale_fill_manual(name="", values=c("white","red"))

这篇关于从两个数据帧构建图时的ggplot图例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆