【问题标题】:percentage plot using ggplot2使用ggplot2的百分比图
【发布时间】:2022-01-01 08:21:42
【问题描述】:

我想绘制如下图所示的内容,但出现“stat_count() 只能具有 x 或 y 美学”的错误。所以我把它改成stat="identity"。但是结果和我在网上找的例子不一样。

网上找到的例子:

示例来自:https://sebastiansauer.github.io/percentage_plot_ggplot2_V2/

我的代码

  geom_bar(aes(y=pct_change, fill=factor(Year)), stat="count")+
  geom_text(aes( label = scales::percent(pct_change),
                 y= pct_change ), stat= "count", vjust = -.5) +
  ylab("Avg Unit Price")  +
  facet_grid(~Type.of.Sale) +
  scale_y_continuous(labels = scales::percent)

【问题讨论】:

    标签: r ggplot2


    【解决方案1】:

    以下是mtcars 数据集的示例,您可以如何完成任务:

    library(tidyverse)
    ggplot(mtcars, aes(x = cyl, group=am))+
      geom_bar(aes(y=..prop.., fill=factor(..x..)), stat="count")+
      geom_text(aes( label = scales::percent(..prop..),
                     y= ..prop..), stat= "count", vjust = -.5) +
      ylab("Avg Unit Price")  +
      facet_grid(~am) +
      scale_y_continuous(labels = scales::percent)
    

    【讨论】:

    • 感谢您帮助我。但是,要使用 tidyverse 包,我不能同时加载 dplyr 包,否则会显示冲突。我应该怎么做才能同时加载 tidyverse 和 dplyr?
    • dplyrtidyverse 中。因此,如果您自动执行library(tidyverse),则会加载一些其他包,例如dplyrggplottidyr 等。
    • 尽管“stat_count() 只能具有 x 或 y 美学”,但我仍然遇到此错误。
    • dput()您的数据并将其添加到您的问题中。在控制台中写入dput(hereyourdata)。并将输出复制并粘贴到您的问题中作为编辑。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-01-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-17
    • 2022-12-23
    • 2023-01-29
    相关资源
    最近更新 更多