make paired, inverted histograms

2020-07-18 02:57发布

I would like to make paired dotplot histograms for two groups across a set of different tests with the two groups shown in opposite directions on the y-axis. Using this simple data set

dat <- data.frame(score = rnorm(100), group = rep(c("Control", "Experimental"), 50), test = rep(LETTERS[1:2], each=50))

I can make faceted dotplots like this

ggplot(dat, aes(score, fill=group)) + facet_wrap(~ test) + geom_dotplot(binwidth = 1, dotsize = 1)

faceted dotplot example

but I want the Control dots to be pointing down rather than up. Using this question and answer, I can make a histogram version that looks more or less like what I want

ggplot() + 
  geom_histogram(data=subset(dat, group=="Experimental"), aes(score, fill="Experimental", y= ..count..)) +
  geom_histogram(data=subset(dat, group=="Control"), aes(score, fill="Control", y= -..count..)) +
  scale_fill_hue("Group")

paired, inverted histograms but now the faceting is gone. I know I could do the faceting manually using grid.arrange, but that would be laborious (my actual data set has many tests, not just 2), is there a more elegant solution?

Two follow-up questions:

  1. geom_histogram is giving me a warning that says "Stacking not well defined when ymin != 0". Does anyone know how "not well defined" it is? In other words, is this something I should be concerned about?
  2. I'd prefer to use dotplot instead of histogram, but the inversion doesn't seem to work for dotplot. Why is that? Any ideas how to get it to work?

Thanks in advance!

标签: r ggplot2
1条回答
家丑人穷心不美
2楼-- · 2020-07-18 03:41

A careful reading of geom_dotplot will pay dividends:

ggplot() +
  facet_wrap(~test) +
  geom_dotplot(data=subset(dat, group=="Experimental"), aes(score, fill="Experimental")) +
  geom_dotplot(data=subset(dat, group=="Control"), aes(score, fill="Control"),stackdir = "down") +
  scale_fill_hue("Group")

enter image description here

I didn't know of the stackdir argument off the top of my head. I had to look it up!

查看更多
登录 后发表回答