【问题标题】:Several labels while using geom_text function使用 geom_text 函数时的几个标签
【发布时间】:2020-10-12 09:18:03
【问题描述】:

我正在使用以下代码,并且我希望每个条形都有一个标签来指示该条形的值,而不是如下所示的多个标签。有人可以帮忙吗?

    ggplot(data = iris, aes(x = Species , y = Sepal.Length, fill = Species)) +
      geom_bar(stat = "summary",
               show.legend = T,
               fun = mean) +
      ylab("Sepal Length") + xlab("Types of Species") +
      ggtitle('Sepal Length vs Species') +
      scale_fill_manual("legend",
                        values = c(
                          "setosa" = "black",
                          "versicolor" = "orange",
                          "virginica" = "blue"
                        )) + geom_text(aes(label = Sepal.Length))

【问题讨论】:

    标签: r ggplot2 label geom-text


    【解决方案1】:

    你可以试试这个:

    ggplot(data = iris, aes(x = Species , y = Sepal.Length, fill = Species)) +
      geom_bar(stat = "summary",
               show.legend = T,
               fun = mean) +
      ylab("Sepal Length") +
      xlab("Types of Species") +
      ggtitle('Sepal Length vs Species') +
      scale_fill_manual("legend",
                        values = c(
                          "setosa" = "black",
                          "versicolor" = "orange",
                          "virginica" = "blue"
                        )) +
      geom_text(aes(label = round(..y.., 2)), 
                stat = "summary",
                vjust = -.5)
    

    【讨论】:

    • 嗨,Ronak,谢谢,这行得通。我对 R 很陌生,你能帮我知道 ..y.. 是什么意思吗?
    • 为了直接从数据集中引用变量,列名被用作美学(例如 aes(x = Species))。 geom_bar 不能直接使用这些变量,需要以mean、count orsum 的形式计算审美。在您的情况下,geom_bar计算了每个物种的平均值。 ..y.. 指的是这个计算出来的美学。所以如果你想使用geom_barstat_xxx计算的值,你需要使用..*calculated value*..
    • 作为一种解决方法,您可以在创建绘图之前计算均值。然后你可以直接使用这些包含手段的列名。 iris %>% group_by(Species) %>% summarise(Sepal.Length = mean(Sepal.Length)) %>% ggplot(aes(x = Species, y = Sepal.Length, fill = Species)) + geom_col() + geom_text(aes(label = Sepal.Length))
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-08
    • 2018-11-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多