2016-04-24 68 views
1

我有一個離散x軸的繪圖,我想調整刻度兩邊的額外空間,使其在左側變小並且在右側更大,所以長標籤將適合。 scale_x_discrete(expand=c(0, 1))不是我的朋友,因爲它總是在雙方同時工作。 This question是類似的,但地址是連續的。在離散ggplot x軸的兩側添加不同數量的額外空間

我該如何做到這一點?

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

回答

3

這可能是你在找什麼:

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