在离散ggplot x轴的两侧添加不同数量的额外空间

时间:2016-04-24 13:08:51

标签: r ggplot2

我有一个带有离散x轴的图,我想调整刻度两侧的额外空间,使其在左侧较小而在右侧较大,因此长标签适合。 scale_x_discrete(expand=c(0, 1))在这里不是我的朋友,因为它始终同时在双方都有效。 This question类似,但涉及连续的比例。

我该如何实现?

set.seed(0)
L <- sapply(LETTERS, function(x) paste0(rep(x, 10), collapse=""))
x <- data.frame(label=L[1:24], 
                g2 = c("a", "b"),
                y = rnorm(24))
x$g2 <- as.factor(x$g2)
x$xpos2 <- as.numeric(x$g2) + .25

# two groups
ggplot(x, aes(x=g2, y=y)) + 
  geom_boxplot(width=.4) +
  geom_point(col="blue") +
  geom_text(aes(x=xpos2, label=label, hjust=0)) 

enter image description here

1 个答案:

答案 0 :(得分:4)

这可能是您正在寻找的:

library(ggplot2)
set.seed(0)
L <- sapply(LETTERS, function(x) paste0(rep(x, 10), collapse=""))
x <- data.frame(label=L[1:24], 
                g2 = c("a", "b"),
                y = rnorm(24))
x$g2 <- factor(x$g2, levels=c("a", "b", "c"))
x$xpos2 <- as.numeric(x$g2) + .25


# two groups
ggplot(x, aes(x=g2, y=y)) + 
  geom_boxplot(width=.4) +
  geom_point(col="blue") +
  geom_text(aes(x=xpos2, label=label, hjust=0)) +
  scale_x_discrete(expand=c(0.1,0),
                   breaks=c("a", "b"),
                   labels=c("a", "b"),
                   limits=c("a", "b", "c"), drop=FALSE)

enter image description here