【问题标题】:How do I add count label to an axis?如何将计数标签添加到轴?
【发布时间】:2020-06-22 22:32:27
【问题描述】:

我使用 ggplot 创建了这个条形图。我必须创建自己的计数函数并将其命名为“a”,但现在该轴的标签只有一个 a,没有其他内容......我该如何解决?

a <- count(df, glass)

gl <- ggplot(df, aes(x=glass, y="a", fill=glass)) + 
    geom_bar(stat="identity") + 
    theme(axis.text.x=element_text(angle=90,hjust=1,vjust=0.5)) + 
    xlab("Glass type") + 
    ylab("Count") + 
    coord_flip() + 
    theme_minimal() + 
    theme(legend.position = "none") 
gl 

这是我的图表

【问题讨论】:

  • 如果您包含一个简单的reproducible example,其中包含可用于测试和验证可能解决方案的示例输入和所需输出,则更容易为您提供帮助。
  • 如果您希望 ggplot2 为您计算,请尝试使用 geom_bar() 而不使用 y,然后从栏层中删除 stat = "identity"

标签: r ggplot2


【解决方案1】:

geom_bar 的默认统计值是“count”,这意味着geom_bar() 使用stat_count() 来计算每个 x 值的行数,在这种情况下是 glass。使用 stat="identity" 将覆盖默认的 geom_bar() stat 并要求您提供 y 值以进行聚合。我不相信你正在尝试这样做。

尝试以下方法,看看它是否是您想要的:

gl <- ggplot(df, aes(x=glass, fill=glass)) + 
        geom_bar() + 
        theme(axis.text.x=element_text(angle=90,hjust=1,vjust=0.5)) + 
        xlab("Glass type") + 
        ylab("Count") + 
        coord_flip() + 
        theme_minimal() + 
        theme(legend.position = "none")

【讨论】:

    猜你喜欢
    • 2016-01-13
    • 1970-01-01
    • 1970-01-01
    • 2015-05-23
    • 1970-01-01
    • 2020-02-19
    • 2019-12-24
    • 1970-01-01
    • 2019-08-23
    相关资源
    最近更新 更多