【问题标题】:ggplot2 with summarize as y aesthetic - rggplot2 总结为 y 美学 - r
【发布时间】:2020-04-11 13:21:38
【问题描述】:

这是我的任务:

创建以下图表:

  • 按 type1 和 is_legendary 对 Pokemon 数据进行分组
  • 用攻击的平均值总结数据
  • 创建一个条形图,x 为 type1,y 为攻击的平均值,然后输入其中一个填充
  • 将类型一的颜色更改为 type_color
  • facet_wrap 以便常规和传奇口袋妖怪有不同的条形图

我能够通过攻击的平均值来总结数据,但它不是我数据集中的一列。我如何做到这一点,所以攻击的意思是 y 美学?我是否忽略了一种更简单的方法?

我尝试在原始 Pokemon 数据集上创建一个新列,但这会创建所有数据的平均值,而不是按 type1 或 is_legendary 分组。

我也不断收到错误:错误:stat_count() 不得与任何美学一起使用。 但是当我查看该错误时,我看不出它如何应用于这个特定问题.


pokemon$type1 <- factor(pokemon$type1)
pokemon$is_legendary <- factor(pokemon$is_legendary)

pokemon %>% 
  group_by(type1, is_legendary) %>%  
  summarize(mean_attack = mean(attack)) %>% 
  ggplot(mapping = aes(x = type1, y = mean_attack, fill = type1)) + geom_bar() 
+ scale_fill_manual(values = type_color) + facet_wrap(~ is_legendary) 
+ labs(title = "Average Attack of Legendary and Regular Pokemon") + pokemon.theme

【问题讨论】:

  • 一个小提示,如果您将汇总数据通过管道传输到 ggplot(),您可能不想同时将原始 pokemon 数据框作为您的数据源。
  • 如果您想给出 y 坐标,请使用 geom_colgeom_bar 用于当您希望 ggplot 为您汇总计数时
  • 这里是one 的几个 SO 帖子,您可以通过搜索错误消息获得。除此之外,您可以将其设为reproducible example

标签: r ggplot2 dplyr summarize


【解决方案1】:

geom_bar (https://ggplot2.tidyverse.org/reference/geom_bar.html) 的数据表中所述:

geom_bar() 默认使用 stat_count() :它计算每个 x 位置的案例数。 geom_col() 使用 stat_identity():它使数据保持原样。

这是您尝试获取的示例(使用 iris 数据集):

library(tidyverse)
iris %>% group_by(Species) %>% summarise(MeanSep = mean(Sepal.Length))

# A tibble: 3 x 2
  Species    MeanSep
  <fct>        <dbl>
1 setosa        5.01
2 versicolor    5.94
3 virginica     6.59

如果您尝试使用geom_bar 绘制它,您会得到:

iris %>% group_by(Species) %>% summarise(MeanSep = mean(Sepal.Length)) %>% 
  ggplot(., aes(x = Species, y = MeanSep, fill = Species)) +
  geom_bar()

Error: stat_count() must not be used with a y aesthetic.

但是,如果您尝试使用 camille 提到的 geom_col,或者您使用 `geom_bar(stat = "identity") 您会得到您的情节:

iris %>% group_by(Species) %>% summarise(MeanSep = mean(Sepal.Length)) %>% 
  ggplot(., aes(x = Species, y = MeanSep, fill = Species)) +
  geom_col()

iris %>% group_by(Species) %>% summarise(MeanSep = mean(Sepal.Length)) %>% 
  ggplot(., aes(x = Species, y = MeanSep, fill = Species)) + 
  geom_bar(stat = "identity")

希望它能回答你的问题

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-02-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多