2016-08-10 32 views
2

繼在這裏很好的例子: Create stacked barplot where each stack is scaled to sum to 100%操縱Y軸的限制無法正常工作(百分之GGPLOT2條形圖)

我產生barplot我的數據,其結果表示爲百分比。

我的數據幀是:

small_df = data.frame(type = c('A','A','B','B'), 
         result = c('good','bad','good','bad'), 
         num_cases = c(21,72,87,2)) 

而我試圖畫看上去像這樣:

library(scales) 
library(ggplot2) 

ggplot(small_df,aes(x = type, y = num_cases, fill = result)) + 
    geom_bar(position = "fill",stat = "identity") + 
    scale_y_continuous(labels = percent, breaks = seq(0,1.1,by=0.1)) 

這一切工作正常,併產生像這樣一個身影: enter image description here

但是,我想讓y軸的極限值爲0-110%(我稍後會在頂部添加一個標籤,以便我需要該空間)。更改行:

scale_y_continuous(labels = percent, breaks = seq(0,1.1,by=0.1), limits = c(0,1.1)) 

失敗,出現以下錯誤:

Error: missing value where TRUE/FALSE needed

不知道如何解決這個問題?

非常感謝!

回答

1

您可以通過oob更改超出範圍選項或使用coord_cartesian來設置限制。見信息here

ggplot(small_df, aes(x = type, y = num_cases, fill = result)) + 
    geom_bar(position = "fill", stat = "identity") + 
    scale_y_continuous(labels = percent, breaks = seq(0, 1.1, by=0.1), 
        oob = rescale_none, limits = c(0, 1.1)) 

ggplot(small_df, aes(x = type, y = num_cases, fill = result)) + 
    geom_bar(position = "fill", stat = "identity") + 
    scale_y_continuous(labels = percent, breaks = seq(0, 1.1, by=0.1)) + 
    coord_cartesian(ylim = c(0, 1.1)) 

enter image description here

+0

美麗!謝謝! –