离散轴的间距与分类变量的关系 [英] Spacing of discrete axis by a categorical variable
问题描述
我有一个分类轴,我想在该轴上目视分离该分类变量中的组.我不想刻面,因为它占用了太多空间并且在视觉上还不那么干净.
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.
这是我想要的视觉示例,涉及一些乏味的黑客(将用于间隔的非数据条目的alpha设置为0).
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)))
推荐答案
您可以通过scale_x_discrete
的breaks
和limits
参数获得所需的结果.如果需要,将breaks
设置为x轴上的因子水平,将limits
设置为带垫片的因子水平.
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.
这里是一个例子:
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]))
这篇关于离散轴的间距与分类变量的关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!