Avoid plot overlay using geom_point in ggplot2

2019-05-22 23:36发布

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

boxplot with overlaid points

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条回答
爱情/是我丢掉的垃圾
2楼-- · 2019-05-23 00:09

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:

enter image description here

查看更多
登录 后发表回答