[英]In R, how do I create a bar graph using a categorical x and the average of a numeric y with ggplot2?
I am using R version 3.5.1.我正在使用 R 版本 3.5.1。
I started with this problem , and used the code suggested by the top comment on my own dataset, where time_len
is a categorical variable telling how long it takes to play game i, with values of short, medium, and long;我从这个问题开始,并在我自己的数据集上使用了顶部评论建议的代码,其中
time_len
是一个分类变量,表示玩游戏 i 需要多长时间,值分别为 short、medium 和 long; num_fans
is a numeric variable telling how many fans game i has: num_fans
是一个数字变量,表示我有多少粉丝游戏:
ggplot(cdata) +
aes(x = time_len, y = num_fans) +
geom_bar(stat = "identity")
Here is the plot:这是情节:
I created the bar chart using the code above, but the problem is that the num_fans
variable looks like it is a total.我使用上面的代码创建了条形图,但问题是
num_fans
变量看起来像是一个总数。 I want it to show the average for each category.我希望它显示每个类别的平均值。
EDIT: here is a sample of my data.编辑:这是我的数据示例。
game_id min_players single_player max_players family_game avg_time time_len year life avg_rating
1 161936 2 multi 4 family 60 short 2015 4 8.65105
2 187645 2 multi 4 family 240 long 2016 3 8.45420
3 12333 2 multi 2 small 180 long 2005 14 8.32843
4 193738 2 multi 4 family 150 medium 2016 3 8.28646
5 162886 1 single 4 family 120 medium 2017 2 8.39401
6 84876 2 multi 4 family 90 medium 2011 8 8.12803
geek_rating rating age owned num_fans
1 8.49375 8.572400 13 47498 2168
2 8.16391 8.309055 14 23989 1594
3 8.18051 8.254470 13 45955 3639
4 8.07144 8.178950 12 21513 835
5 7.96162 8.177815 13 13743 1002
6 8.01120 8.069615 12 49353 1866
Again, I am only asking about time_len.同样,我只询问 time_len。 Is there a way to show the average of
num_fans
?有没有办法显示
num_fans
的平均值?
Try replacing the尝试更换
geom_bar(stat = "identity")
line with符合
stat_summary(geom = "bar", fun.y = "mean")?
(Note: this is the answer contributed by Z.Lin, who told me that I could post it as an answer.) (注意:这是 Z.Lin 提供的答案,他告诉我可以将其发布为答案。)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.