r - ggplot2 总结为 y 美学 - r
问题描述
这是我的任务:
创建以下图表:
- 按 type1 和 is_legendary 对 Pokemon 数据进行分组
- 用攻击的平均值总结数据
- 在 x 上创建一个带有 type1 的条形图,在 y 上使用攻击的平均值并键入一个填充
- 将类型一的颜色更改为 type_color
- facet_wrap 以便常规和传奇口袋妖怪有不同的条形图
我可以通过攻击来总结数据,但它不是我数据集中的一列。我如何做到这一点,所以攻击的意思是 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
解决方案
如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.
但是,如果你正在尝试使用geom_col
camille 提到的,或者你使用 `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")
希望它能回答你的问题
推荐阅读
- azure - 将 Azure IoT sdk-c 移植到 yocto 系统
- angular - Proxy.config.js 配置无法正常工作
- laravel - 流明调度程序在 null 上调用成员函数 connection()
- tensorflow - '进程以退出代码 -1073741571 (0xC00000FD) 结束'当使用 tensorflow 作为后端在 keras 中训练 CNN 时
- javascript - 如何通过 Kendo Grid 中的自定义过滤来保留以前的过滤器值?
- git - 在 GitHub 上禁用创建存储库按钮
- python-3.x - 在嵌套函数中传递 self 有意义吗?
- pyspark - Pyspark groupby 和计数空值
- python - Pandas 手动计算方差
- mysql - Laravel 从关系表中获取数据