2012-09-27 59 views
7

我正在試圖在ggplot2中繪製水平箱圖,只能使用coord_flip()進行繪圖。我也試圖垂直放置箱形圖以將某些組合在一起。我已經閱讀過這種類型的建議,但這與coord_flip()不兼容,正如我們在這裏看到的:ggplot2: boxplot with facet_grid and free scale。所以我想知道是否可以使用空白級別來創建空格。以下是我已經設法到目前爲止做:在ggplot2中定位水平箱圖

d <- diamonds 
library("ggplot2") 
levels(d$cut) <- list(A="Fair", B="Good", "-", C="Very Good", D="Ideal", E="Premium") 
p = ggplot(d, aes(x=cut, y=depth)) 
p + 
    geom_boxplot(color="black", size=0.2) + 
    theme_bw() + 
    scale_x_discrete(breaks = c("A", "B", "-", "C", "D", "E"), drop=FALSE) + 
    coord_flip() 

ph = 2.75 
pw = 4 
ggsave("plot.png", height=ph, width=pw) 

正如你可以看到,如果我創建一個空白的水平「 - 」它,並將其納入scale_x_discrete(),然後以某種方式得到了一個空白行。問題是我只能添加一個空格。有沒有人有任何想法如何在這些水平方塊圖之間添加空格?

回答

3

這裏,可以讓你增加更多的空白水平的一種方法:

d <- diamonds 
levels(d$cut) <- list(A="Fair", B="Good", " "="space1", C="Very Good", D="Ideal", " "="space2", E="Premium") 
ggplot(d, aes(x=cut, y=depth)) + 
    geom_boxplot(color="black", size=0.2) + 
    theme_bw() + 
    scale_x_discrete(breaks = c("A", "B", " ", "C", "D", " ", "E"), drop=FALSE) + 
    coord_flip() 

這將使打勾的間隔標記爲好,但:

plot with tick marks

刪除所有蜱簡單加入:

+ theme(axis.ticks.y = element_line(linetype=0)) 

plot without tick marks

但是,如果你想刪除刻度線只爲間隔,至少有一種方式(我敢肯定有其他人)與自定義功能做到這一點:

f <- function(x) { 
    x[!x %in% c("A", "B", "C", "D", "E")] <- NA 
    x 
} 

ggplot(d, aes(x=cut, y=depth)) + 
    geom_boxplot(color="black", size=0.2) + 
    theme_bw() + 
    scale_x_discrete(breaks=f, drop=FALSE) + 
    coord_flip() 

plot with some tick marks