ggplot:将新数据添加到现有的分组箱图中 [英] ggplot: adding new data to the existing grouped boxplot
问题描述
我用ggplot2创建了一个分组的箱线图。现在,我想通过以下方式向现有绘图中添加其他数据:每个月
我有一个最佳值,该值应显示为点,并且应将这些点连接起来一行。这是所需的状态:
I created a grouped boxplot with ggplot2. Now I want to add additional data to the existing plot in the following way: for each month I have one "Optimal" value that should be displayed as a dot and these dots should be connected by a line. This is the desired state:
如何将这些点和线添加到绘图中?
我是否可以将连接线放在盒图中?
How could I add those dots and lines to my plot? Can I by any chance put the connecting lines behind the boxplots?
这是我当前的状态和数据:
Here is my current state and the data:
-
不带点的ggplot:
Ggplot without dots :
数据框:数据框
R代码:
data("MyData")
MyData$Month <- as.factor(MyData$Month)
head(MyData)
MyPlot <- ggplot(MyData, aes(x=Month, y=Note, fill=Treatment)) +
geom_boxplot()
MyPlot
谢谢!
推荐答案
只需添加将y映射到其他变量的geom。为简单起见,我将一些美学元素移至geom_boxplot。
Simply add an geom mapping the y to a different variable. For the sake of simplicity, I moved some of the aesthetics to the geom_boxplot.
MyPlot <- ggplot(MyData, aes(x=Month)) + geom_boxplot(aes(y=Note, fill=Treatment)
MuPlot <- MyPlot + geom_pointline(aes(y=Optimum), colour="green", stroke="black")
但是,这不会为您添加图例,因为ggplot2不支持相同比例的多种编码(即同时使用处理和单独的颜色变量)。
This will however not add you points to the legend, as ggplot2 does not support multiple encodings of the same scale (i.e. using both Treatment and a separate variable for colour).
geom geom_pointline
来自柠檬
The geom geom_pointline
is from the 'lemon' package.
第二点,尝试第二行:
MuPlot <- MyPlot + geom_pointline(aes(y=Optimum, colour="Optimum"), stroke="black") + scale_colour_manual(values('Optimum'='green'))
这篇关于ggplot:将新数据添加到现有的分组箱图中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!