R:如何将箱线图和点图画在一幅图上

新的10年第一篇推送来了,这次我当了回R画图代码的搬运工,这次我们来讨论下如何将箱线图和点图画在一幅图上:我们借用示例数据来说话:


示例data

好,我们上代码:

library(gcookbook) 
data(heightweight) #示例数据

#以sex为分类横坐标
ggplot(heightweight, aes(x = sex, y = heightIn)) +
  geom_boxplot(aes(x = as.numeric(sex) + .2, group = sex), width = .25) +
  geom_dotplot(
    aes(x = as.numeric(sex) - .2, group = sex),
    binaxis = "y",
    binwidth = .5,
    stackdir = "center"
  ) +
  scale_x_continuous(
    breaks = 1:nlevels(heightweight$sex),
    labels = levels(heightweight$sex)
  )  #将连续型横坐标改变文字,以sex作为文字指标
效果图

我在推特上还看见另外一种写法

d <-  data.frame(y = rnorm(20, 9, 2),
               group = as.factor(rep(c('Post-FAP', 'Post-DEP'), each = 10)),
               id = rep(1:10, 2))

ggplot(d, aes(y = y)) +
 geom_boxplot(aes(x = rep(c(-3, 3), each = 10), group = group), fill = 'steelblue') +
 geom_point(aes(x = rep(c(-1, 1), each = 10)), size = 5)

这种写法将点图和箱线图以坐标区分开了,效果图:


效果图

感觉还可以哈,重申一下,我是小潤澤,我为自己带盐。

参考:
https://r-graphics.org/recipe-distribution-dot-plot-multi

https://stackoverflow.com/questions/31102162/r-paired-dot-plot-and-box-plot-on-same-graph-is-there-a-template-in-ggplot2?utm_source=dlvr.it&utm_medium=twitter

你可能感兴趣的:(R:如何将箱线图和点图画在一幅图上)