1
votes

I'm trying to make a ggplot with some data, filling the dots with a factor variable. I'll write here a small example to explain myself.


drap = tibble(id = c("S1", "S2", "S3" , "S4", "S5", "S6", "S7", "S8"), 
              ret =c (123, 555, 763, 113, 415, 121, 221, 531),
              cod = c(1, 5, 1, 3, 5, 1, 5, 8))

#here the "cod" column is converted to a factor with 9 levels (0 to 8).
drap$cod = factor(drap$cod, levels = c(0:8), ordered = TRUE)


plot = ggplot(drap) + geom_count(mapping=aes(x= id, y=ret, fill = cod))
ggplotly(plot)

The factor() function works well (I can see all the levels) but the problem is after. When I make the plot, the legend has only values presented in the database (so 1,3,5,8). I want to show a legend with all the factor levels (0:8). I discovered that using the function levels() I can save the factor levels, but I don't know what to do next.

Of course this is a small example and everything should work also in shiny.

EDIT: For those interested in the problem, I've found a solution with ggplot but if you want to use ggplotly() it doesn't work. The @duck solution works fine as long as you have the same data as input. If you want to change for example the variables, it doesn't work anymore (at least without a lot of if conditions). So a "reactive" solution is to use DROP=FALSE inside ggplot. Unfortunately for now plotly doesn't support this function.

1

1 Answers

2
votes

Try this:

library(ggplot2)
#Code
ggplot(drap) + geom_count(mapping=aes(x= id, y=ret, fill = cod))+
  scale_fill_discrete(limits=factor(c(0:8)))

Output:

enter image description here