绘制ggplot2中每个级别的平均值 [英] Plotting the average values for each level in ggplot2
问题描述
I'm using ggplot2 and am trying to generate a plot which shows the following data.
我使用ggplot2,并试图生成一个显示以下数据的图。 (分数= c(4,2,3,5,7,6,5,6,4,2,3,5,4,8),
年龄= c(18,18,23,50, 19,39,19,23,22,22,40,35,22,16))
str(df)
df
df=data.frame(score=c(4,2,3,5,7,6,5,6,4,2,3,5,4,8),
age=c(18,18,23,50,19,39,19,23,22,22,40,35,22,16))
str(df)
df
我不想做变量的频率图(见下面的代码),而是想要生成每个x值的平均值图。所以我想绘制每个年龄段的平均分数。在x轴上18岁时,我们可能在y轴上有一个 3 的分数。在23岁时,我们可能会得到 4.5 的平均分,等等(更正<编辑:平均值)。这可以用barplot来表示。
Instead of doing a frequency plot of the variables (see below code), I want to generate a plot of the average values for each x value. So I want to plot the average score at each age level. At age 18 on the x axis, we might have a 3 on the y axis for score. At age 23, we might have an average score of 4.5, and so forth (Edit: average values corrected). This would ideally be represented with a barplot.
ggplot(df, aes(x=factor(age), y=factor(score))) + geom_bar()
Error: stat_count() must not be used with a y aesthetic.
不知道如何在R中使用ggplot2来做到这一点,并且似乎无法找到这样的东西地块。在统计上,我不知道我希望绘制的情节是否是正确的选择,但这是另一个商店。
Just not sure how to do this in R with ggplot2 and can't seem to find anything on such plots. Statisticially, I don't know if the plot I desire to plot is even the right thing to do, but that's a different store.
谢谢!
推荐答案
另一个解决方案
Another solution
ggplot(df, aes(x=factor(age), y=score)) + stat_summary(fun.y="mean", geom="bar")
这篇关于绘制ggplot2中每个级别的平均值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!