r / ggplot - 使用position_jitterdodge,没有填充美学

时间:2015-06-09 14:36:18

标签: r ggplot2

geom_pointposition_jitterdodge一起使用仅在设置填充美学时有效。我不明白为什么会这样!

此命令

library(ggplot2)
ggplot(diamonds[ sample(nrow(diamonds), 1000), ], 
       aes(x = cut, y = carat, color = clarity)) +
  geom_point(shape = 21, position = position_jitterdodge())

产生错误:

Error: position_jitterdodge requires the following missing aesthetics: fill

但这有效:

ggplot(diamonds[ sample(nrow(diamonds), 1000), ], 
       aes(x = cut, y = carat, fill = clarity)) +
  geom_point(shape = 21, position = position_jitterdodge())

enter image description here

简单地提供NA值来填补并不是一个可行的解决方法:

ggplot(diamonds[ sample(nrow(diamonds), 1000), ], 
       aes(x = cut, y = carat, color = clarity, fill=NA)) +
  geom_point(shape = 21, position = position_jitterdodge())

> Error in seq.default(h[1], h[2], length = n) : 
  'to' cannot be NA, NaN or infinite

虽然它可以指定一个任意常量(原谅可怕的结果):

ggplot(diamonds[ sample(nrow(diamonds), 1000), ], 
       aes(x = cut, y = carat, color = clarity, fill='constant')) +
  geom_point(shape = 21, position = position_jitterdodge())

enter image description here

关于如何在不指定填充的情况下使用抖动/闪避的任何想法? (即仅有色点)

编辑:进一步对@joran的评论,我想在点图上叠加点。由于没有必要使用fill来区分箱图,如果geom_point(position=position_jitterdodge())容纳了没有fill的图表,那就太棒了。也许目前不可能,但是......

#This doesn't work:
ggplot(diamonds[ sample(nrow(diamonds), 1000), ], 
       aes(x = cut, y = carat, color = clarity)) +
  geom_boxplot() +
  geom_point(shape = 21, position = position_jitterdodge())

#This does, although obviously no one wants a plot like this
ggplot(diamonds[ sample(nrow(diamonds), 1000), ], 
       aes(x = cut, y = carat, color = clarity, fill='constant')) +
  geom_boxplot() +
  geom_point(shape = 21, position = position_jitterdodge())

#This is way it's intended to work, but marries you to 'fill'
ggplot(diamonds[ sample(nrow(diamonds), 1000), ], 
       aes(x = cut, y = carat, fill = clarity)) +
  geom_boxplot() +
  geom_point(shape = 21, position = position_jitterdodge())

1 个答案:

答案 0 :(得分:6)

好的,这是我的解决方法。指定fill以及您真正想要的美学(在我的情况下为color),然后填空scale_fill_manual

我制作了一个与我的实际用例更相似的不同假数据集,因为上面指定的钻石数据实际上并不是箱子+点数的好选择

my_dat <- data.frame(class=factor(rep(1:2, 600)),
                     y=rnorm(1200)),
                     x=rep(letters[1:3], each=400))

ggplot(my_dat, aes(x=x, y=y, fill=class, color=class)) +
  geom_boxplot(outlier.shape = NA) +
  geom_point(shape = 21, alpha = 0.5, position=position_jitterdodge()) +
  scale_fill_manual(values = rep(NA, 2)) 

enter image description here