ggplot: adding new data to the existing grouped boxplot

时光总嘲笑我的痴心妄想 提交于 2020-02-24 12:09:30

问题


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:

  1. Ggplot without dots :

  2. Data frame:Data frame

R Code:

data("MyData")
MyData$Month <- as.factor(MyData$Month)

head(MyData)

MyPlot <- ggplot(MyData, aes(x=Month, y=Note, fill=Treatment)) + 
  geom_boxplot()   
MyPlot

Thank you in advance!


回答1:


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")

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).

The geom geom_pointline is from the 'lemon' package.

On a second note, try this for the second line:

MuPlot <- MyPlot + geom_pointline(aes(y=Optimum, colour="Optimum"), stroke="black") + scale_colour_manual(values('Optimum'='green'))


来源:https://stackoverflow.com/questions/53153701/ggplot-adding-new-data-to-the-existing-grouped-boxplot

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!