dotplot dot not showing up and format of dot plot

时间:2015-09-01 22:06:12

标签: r ggplot2 mosaic-plot

How can I show the dots colored using the mosaic package to do a dotplot?

library(mosaic)
n=500
r =rnorm(n)
d = data.frame( x = sample(r ,n= 1,size = n, replace = TRUE), color = c(rep("red",n/2), rep("green",n/2)))
dotPlot(d$x,breaks = seq(min(d$x)-.1,max(d$x)+.1,.1))

right now all the dots are blue but I would like them to be colored according to the color column inthe data table

2 个答案:

答案 0 :(得分:3)

如果您仍然对mosaic / lattice解决方案感兴趣而不是ggplot2解决方案,请点击此处。

dotPlot( ~ x, data = d, width = 0.1, groups = color, 
  par.settings=list(superpose.symbol = list(pch = 16, col=c("green", "red"))))

resulting plot

另请注意

  • ggplot2一样,颜色不是由color变量中的值决定,而是由主题决定。您可以使用par.settings在绘图级别修改此内容,或trellis.par.set()更改默认值。
  • 最好使用公式和data =,以避免使用$运算符。
  • 如果要设置bin宽度,可以使用width参数而不是breaks。 (如果对您有意义,您可以使用center参数来控制垃圾箱的中心。默认情况下,0将是垃圾箱的中心。)

答案 1 :(得分:1)

You need to add stackgroups=TRUE so that the two different colors aren't plotted on top of each other.

n=20
set.seed(15)
d = data.frame(x = sample(seq(1,10,1), n, replace = TRUE), 
               color = c(rep("red",n/2), rep("green",n/2)))
table(d$x[order(d$x)])
length(d$x[order(d$x)])
binwidth= 1

ggplot(d, aes(x = x)) + 
  geom_dotplot(breaks = seq(0.5,10.5,1), binwidth = binwidth, 
               method="histodot", aes(fill = color),
               stackgroups=TRUE) +
  scale_x_continuous(breaks=1:10)

Also, ggplot uses its internal color palette for the fill aesthetic. You'd get the same colors regardless of what you called the values of the "color" column in your data. Add scale_fill_manual(values=c("green","red")) if you want to set the colors manually.

enter image description here