我是一个绝对的初学者,距离开始使用已有2-3天了ggplot2
。到目前为止,我一直使用Excel来绘制图形。ggplot2真的杀死了我,所以我想到了在这里发布查询。
昨晚,我讨论了如何geom_smooth()
在另一个图层上进行绘图,例如geom_point()
在此处进行了讨论:绘图中使用的美学比例| ggplot2
在此基础上,我想到了尝试多种方法geom_smooth()
。
这是我所做的:
ggplot(mpg, aes(displ, hwy)) +
geom_point(aes(color = class)) +
geom_smooth(method = "loess", se = FALSE, color = "black", aes(linetype = "loes")) +
geom_smooth( method = "lm", se = FALSE, color = "red", aes(linetype = "lm",color = "green")) +
labs(colour = "Method")
它与上一个代码相似,除了我添加了另一个 geom_smooth().
输出为:
我也查看了多层图例的格式图例ggplot2看来我可以手动覆盖颜色。
如我们所见,第三层仍然覆盖第二层的颜色(在图例中)。
所以,这就是我所做的:
ggplot(mpg, aes(displ, hwy)) +
geom_point(aes(color = class)) +
geom_smooth(method = "loess", se = FALSE, color = "123", aes(linetype = "loes")) +
geom_smooth( method = "lm", se = FALSE, color = "345", aes(linetype = "lm",color = "green")) +
scale_colour_manual(values=c("coral", "chocolate", "cornsilk", "papayawhip", "blanchedalmond","red","black","yellow","pink")) +
labs(colour = "Method")
第三层仍将覆盖第二层的颜色(在图例中)。多谢您的协助。
我有两个问题:
问题1:我上面发布的问题是否有解决方法?我将不胜感激。有没有解决办法?我将不胜感激。
问题2:我注意到有时人们会使用,aes(linetype = "lm")
而有时他们只是(linetype = "lm")
在内部使用geom_smooth()
。我们为什么要做这个?我相信,如果使用的话,aes(..)
我在这里没有明确的假设,所以我会避免猜测。我会很感激你的想法。
更新:我的问题是关于发布的解决方案。
我们可以不使用任何其他形状的散点图吗?发布的解决方案建议将形状更改为size = 21,这让我有些不舒服。
我将代码(在下面的解决方案中)更改为其他形状,如下所示:
huron <- data.frame(year = 1875:1972, level = as.numeric(LakeHuron))
ggplot(mpg, aes(displ, hwy)) +
# map geom_point class to 'fill'
geom_point(shape=5, aes(color = class)) +
# use color and linetype for geom_smooth
geom_smooth(method = "loess", se = FALSE,
aes(linetype = "loess", color = 'loess')) +
geom_smooth(method = "lm", se = FALSE,
aes(linetype = "lm", color = "lm")) +
# merge linetype and color legends by giving them the same name
scale_linetype_discrete(name = "Method") +
scale_color_manual(name = "Method", values = c("red", "black","coral", "chocolate", "cornsilk", "papayawhip", "blanchedalmond","red","black"))
但是,运行此代码后,我们将看到lm和黄土的颜色已重置为蓝色,并且散点图的图例不再是纯色。我可以更改形状,但不能更改颜色和图例问题。有什么想法吗?
fill
对geom_point和color
geom_smooth使用和空心形状。
huron <- data.frame(year = 1875:1972, level = as.numeric(LakeHuron))
ggplot(mpg, aes(displ, hwy)) +
# map geom_point class to 'fill'
geom_point(shape=21, aes(fill = class), color = NA) +
# use color and linetype for geom_smooth
geom_smooth(method = "loess", se = FALSE,
aes(linetype = "loess", color = 'loess')) +
geom_smooth(method = "lm", se = FALSE,
aes(linetype = "lm", color = "lm")) +
# merge linetype and color legends by giving them the same name
scale_linetype_discrete(name = "Method") +
scale_color_manual(name = "Method", values = c('red', 'black'))
但是,我还要指出,如果希望颜色信息用于区分点类,则平滑线的不同颜色会让人分心。我认为最好将两条平滑线都留成黑色-线型足以区分它们
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句