mjskay / ggdist

Visualizations of distributions and uncertainty
https://mjskay.github.io/ggdist/
GNU General Public License v3.0
834 stars 26 forks source link

Is it possible to automatically color quantile dotplots by the quantile? #139

Closed qdread closed 2 years ago

qdread commented 2 years ago

I am curious whether the color or fill aesthetic for quantile dotplots can be automatically mapped to the quantiles themselves, for instance if I do a 100-quantile dotplot and would like to color the 1st and 100th dots differently than the other ones, within each group.

For example, how would I color the 1st and 100th points from each of these two groups' quantile dotplots a different color than the others?

ggplot(data = data.frame(x = rnorm(2000, mean=c(0,2)), g = c('a','b')), aes(x=x,y=g)) + stat_dotsinterval(quantiles=100)

Thanks for the great package!

mjskay commented 2 years ago

Good question! In future versions this will be easier because I am planning to include the cdf computed variable for dotplots, so you would have access to the cdf variable from which you can determine the quantile associated with each data point.

In the mean time, you can use the (undocumented) fact that a dist column is generated containing a list of distributional objects associated with each distribution that is visualized. While this feature is not documented, I don't expect it to go away any time soon. It does make for a bit of a hackier solution, as it being a list column means you have to use mapply() to get the quantiles (i.e. you can't do quantile(dist, 0.1) you have to do mapply(quantile, dist, 0.1)). This makes for an ugly but workable solution:

data.frame(x = rnorm(2000, mean=c(0,2)), g = c('a','b')) |>
  ggplot(aes(x = x, y = g)) +
  stat_dotsinterval(aes(fill = stat(mapply(quantile, dist, .01) < x & x < mapply(quantile, dist, .99))), quantiles = 100) +
  labs(fill = "q01 < x < q99")

image

As I said, future versions will make this a lot easier, but for now the above solution should work.

qdread commented 2 years ago

This is amazingly helpful, thanks a bunch! I look forward to the shiny new version 😀

mjskay commented 2 years ago

You're welcome!