rggplot2mosaic-plot

dotplot dot not showing up and format of dot 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


Solution

  • 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