【发布时间】:2019-11-08 17:17:10
【问题描述】:
我真的很难为带有黄土回归的geom_point 图设置正确的图例,而使用了 2 个数据集
我有一个数据集,它总结了一天的活动,然后我在同一张图上绘制,记录了每小时和每天的所有活动,加上用黄土函数平滑的回归曲线,加上每一天的每一小时。
更准确地说,这是第一个代码的示例,返回的图形没有图例,这正是我的预期:
# first graph, which is given what I expected but with no legend
p <- ggplot(dat1, aes(x = Hour, y = value)) +
geom_point(color = "darkgray", size = 1) +
geom_point(data = dat2, mapping = aes(x = Hour, y = mean),
color = 20, size = 3) +
geom_smooth(method = "loess", span = 0.2, color = "red", fill = "blue")
和图表(灰色是所有数据,每小时,每天。红色曲线是黄土回归。蓝点是每小时的平均值):
当我尝试设置图例时,我未能绘制一个解释两种点(灰色数据,蓝色平均值)和黄土曲线(红色)的图例。请参阅下面的一些我尝试过的示例。
# second graph, which is given what I expected + the legend for the loess that
# I wanted but with not the dot legend
p <- ggplot(dat1, aes(x = Hour, y = value)) +
geom_point(color = "darkgray", size = 1) +
geom_point(data = dat2, mapping = aes(x = Hour, y = mean),
color = "blue", size = 3) +
geom_smooth(method = "loess", span = 0.2, aes(color = "red"), fill = "blue") +
scale_color_identity(name = "legend model", guide = "legend",
labels = "loess regression \n with confidence interval")
和另一个试验:
# I tried to combine both date set into a single one as following but it did not
# work at all and I really do not understand how the legends works in ggplot2
# compared to the normal plots
A <- rbind(dat1, dat2)
p <- ggplot(A, aes(x = Heure, y = value, color = variable)) +
geom_point(data = subset(A, variable == "data"), size = 1) +
geom_point(data = subset(A, variable == "Moy"), size = 3) +
geom_smooth(method = "loess", span = 0.2, aes(color = "red"), fill = "blue") +
scale_color_manual(name = "légende",
labels = c("Data", "Moy", "loess regression \n with confidence interval"),
values = c("darkgray", "royalblue", "red"))
似乎所有图例设置都以“奇怪”的方式混合在一起,这是一个灰色线覆盖的灰点,然后是蓝色和红色相同(对于 3 个标签)。所有的背景都被填充为蓝色:
【问题讨论】: