操纵Y轴限制不起作用(ggplot2百分比条形图)

时间:2016-08-10 15:02:32

标签: r ggplot2

按照这里的好例子: Create stacked barplot where each stack is scaled to sum to 100%

我为我的数据生成了一个条形图,其结果以百分比形式显示。

我的数据框是:

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))

因以下错误而失败:

  

错误:缺少需要TRUE / FALSE的值

知道如何解决这个问题吗?

非常感谢!!!

1 个答案:

答案 0 :(得分:2)

您可以通过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