2017-06-16 83 views
2

使用這種data.frameGGPLOT2:添加另一個變量作爲第二線x軸標籤

> df 
       var value percent 
1 AAAA BBBB CCCCC -0.5  9 
2 FFFF DDDD CCCCC 0.3  13 
3 BBBB NNNN DDDDD 0.7  17 
4 NNNN MMMM BBBBB -0.4  25 

我要添加的percent和支架之間的符號「這樣(9%)」作爲第二線x軸標籤。

我這樣做是因爲使用這個腳本(以下這個answer

my.labels <- c(
    "AAAA BBBB CCCCC\n(9%)", 
    "FFFF DDDD CCCCC\n(13%)" , 
    "BBBB NNNN DDDDD\n(17%)", 
    "NNNN MMMM BBBBB\n(25%)" 
)  

ggplot(df, aes(x = var, y = value))+ 
    geom_bar(stat ="identity", width = 0.4)+ 
    scale_x_discrete(labels = my.labels) 

它是好的,爲4個變量做如下
enter image description here

只,但如果我有很多的變量,它會需要時間。我認爲應該有一個更快更有效的方法來處理很多變量。任何建議將不勝感激。

回答

3
my.labels <- paste0(df$var, "\n (", df$percent, "%)") 

ggplot(df, aes(x = var, y = value))+ 
    geom_bar(stat ="identity", width = 0.4)+ 
    scale_x_discrete(labels = my.labels) 

enter image description here

編輯:

以上是行不通的,如果直接用facet-wrapscales="free_x"實現:

p <- ggplot(df, aes(x = var, y = value)) + 
    geom_bar(stat ="identity", width = 0.4) 

p + 
    facet_wrap(~var, scales="free_x") + 
    scale_x_discrete(labels = my.labels) 

enter image description here

爲了讓標籤T o顯示正常,首先添加自定義標籤回用facet_wrap變量作爲休息值data.frame

df$lab <- my.labels 

那麼對於scale_x_discrete功能:

p + 
    facet_wrap(~var, scales="free_x") + 
    scale_x_discrete(labels = df$lab, breaks=df$var) 

enter image description here

+0

非常感謝亞當 – aelwan

+0

什麼如果它是一個方面網格,並且我正在使用scales =「free_x」來刪除未使用的級別? – aelwan

+0

@aelwan查看更新的答案 –

相關問題