Avoid plot overlay using geom_point in ggplot2

六月ゝ 毕业季﹏ 提交于 2019-12-22 17:56:18

问题


In ggplot2, geom_point defaults to plotting over the current plot. For example, calling geom_point after a call to geom_boxplot results in the points plotted over the boxplot:

ggplot(iris, aes(x = "All", y = Sepal.Length)) +
  geom_boxplot() +
  geom_point(aes(color=Species), position = "jitter") 

Is there a way to plot the points separately to the side, rather than over the boxplot?

In my particular case I want to do this because the points obscure the plot (even with transparency, etc), a problem that is not an issue with the example dataset here.


回答1:


You can plot them separately by supplying separate x-values for the boxplot and the points:

ggplot(iris, aes(y = Sepal.Length)) +
  geom_boxplot(aes(x="Boxplot")) +
  geom_point(aes(x="Points", color=Species), 
             position = position_jitter(width=0.15, height=0)) 

Another option is to use boxplots by species:

ggplot(iris, aes(y = Sepal.Length)) +
  geom_boxplot(aes(x="All Data"), width=0.5) +
  geom_boxplot(aes(x="By Species", colour=Species), width=0.5,
               position=position_dodge(width=0.6)) 

Here's what the two plots look like:



来源:https://stackoverflow.com/questions/33740803/avoid-plot-overlay-using-geom-point-in-ggplot2

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