首页 > 解决方案 > ggplot2 总结为 y 美学 - r

问题描述

这是我的任务:

创建以下图表:

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

我尝试在原始口袋妖怪数据集上创建一个新列,但这会创建所有数据的平均值,而不是按 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

标签: rggplot2dplyrsummarize

解决方案


geom_barhttps://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.

但是,如果你正在尝试使用geom_colcamille 提到的,或者你使用 `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")

在此处输入图像描述

希望它能回答你的问题


推荐阅读