【问题标题】:Manipulating Y axis limits does not work (ggplot2 percent bar plot)操纵 Y 轴限制不起作用(ggplot2 百分比条形图)
【发布时间】:2016-12-17 01:19:52
【问题描述】:

按照这里的好例子: 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))

这一切都很好,并产生如下图:

但是,我想将 y 轴的限制设为 0-110%(稍后我想在顶部添加一个标签,所以我需要空间)。将行更改为:

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

失败并出现以下错误:

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

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

非常感谢!!!

【问题讨论】:

    标签: r ggplot2


    【解决方案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))
    

    【讨论】:

    • 漂亮!谢谢!
    猜你喜欢
    • 2018-12-15
    • 1970-01-01
    • 2017-08-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-06-06
    • 1970-01-01
    • 2016-10-15
    相关资源
    最近更新 更多