我无法弄清楚如何使用expand()内scale_x_discrete()来扩展分类 x 轴,以便将标签放置在点的右侧不会脱离情节。
我知道如果 x 是数字,我可以简单地调整 x 的最大限制,以便所有点都向左移动。但是,我无法弄清楚如何使用分类变量来做到这一点。我什至不在乎扩展变量标签是否为“”。我只需要在 x 轴上最后一个分类变量的右侧有更多空间。
以下是可用于说明如何成功执行此操作的示例数据:
data(iris)
library(ggplot2)
ggplot(data = iris, aes(x = Species, y = Sepal.Width)) +
geom_jitter()
Run Code Online (Sandbox Code Playgroud)
感谢您的任何帮助,请不要犹豫,提出任何澄清问题!
编辑:绘图以方便视觉解释
由于我面临同样的问题...我发现expand_limits(...)这里非常有用:
dat <- data.frame(x= c('a', 'b', 'c'), y= 1:3)
ggplot(data= dat, aes(x= x, y= y)) +
geom_point() +
expand_limits(x= c(-1, 5))
Run Code Online (Sandbox Code Playgroud)
或者,为了避免对限制进行硬编码:
expand_limits(x= c(-1, length(levels(dat$x)) + 2))
Run Code Online (Sandbox Code Playgroud)
您可以将空白级别附加到分类变量的现有级别,如下所示:
data(iris)
levels(iris$Species) <- c(levels(iris$Species),'') # add blank level
library(ggplot2)
ggplot(data = iris, aes(x = Species, y = Sepal.Width)) +
geom_jitter() +
scale_x_discrete(drop=FALSE) # don't drop unused blank level
Run Code Online (Sandbox Code Playgroud)
更新:或者,如果您真的想通过数值扩展 x 轴,那么您可以首先通过as.integer()以下方式将分类转换为数值:
data(iris)
specVals <- levels(iris$Species)
iris$Species <- as.integer(iris$Species)
library(ggplot2)
ggplot(data = iris, aes(x = Species, y = Sepal.Width)) +
geom_jitter(height=0) + # on 2nd thought -- don't add noise to the quantitative axis
scale_x_continuous(limits=c(min(iris$Species)-0.5,max(iris$Species)+1),
breaks=(min(iris$Species)):(max(iris$Species)+1),
labels=c(specVals,''))
Run Code Online (Sandbox Code Playgroud)