Spacing of discrete axis by a categorical variable

2020-03-26 09:23发布

问题:

I have a categorical axis where i'd like to visually separate groups within that categorical variable. I don't want to facet because it takes up too much space and is visually not as clean.

Here's a visual example of what I want that involves some tedious hacking (setting alpha to 0 for non-data entries used for spacing).

library(ggplot2)
dd <- data.frame(x=factor(c(1,-1,2:10),levels=c(1,-1,2:10)), y=c(1,2,2:10), hidden=as.factor(c(0,1,rep(0,9))))
ggplot(data=dd,aes(x=x,y=y,alpha=hidden)) +
  geom_point() + scale_alpha_manual(values=c("1"=0,"0"=1))  +
  scale_x_discrete(breaks=c(1:10))

I'd like to be able create this plot without having to hack an extra category in (which wouldn't be feasible with the amount of data/number of groups I'm trying to plot) using the following data structure (where the variable "groups" determines where the spacing occurs):

dd2 <- data.frame(x=factor(1:10,), y=c(1:10), groups=c("A",rep("B",9)))

回答1:

You can get the result you are looking for via the breaks and limits arguments to scale_x_discrete. Set the breaks to the levels of the factor on the x-axis and the limits to the factor levels with spacers were you want/need them.

Here is an example:

library(ggplot2)

dd <- data.frame(x = factor(letters[1:10]), y = 1:10)

ggplot(dd) +
  aes(x = x, y = y) +
  geom_point() +
  scale_x_discrete(breaks = levels(dd$x),
                   limits = c(levels(dd$x)[1], "skip", levels(dd$x)[-1]))



标签: r ggplot2