使用ggplot2在R中的 Barplot中的垂直平均线

我对 R 很新,但我试图从 ggplot2 库中创建一个 barplot 中的垂直平均线。

我对 R 很新,但我试图从 ggplot2 库中创建一个 barplot 中的垂直平均线。

我当前的图表是按年份分组的,每个彩色条代表不同的年龄。y 轴是 count:mygraph

我想有一个垂直的平均线为每个组的年(即,平均年龄为 1 年,平均年龄为 2 年,等等)

这是我写到目前为止:

library(ggplot2)
AgeDat<-read.csv(File Name)
columnmeans<-c("MeanValue", "MeanValue", "MeanValue"..."MeanValue")
SepAgePlot<-ggplot(AgeDat, aes(factor(Year), Count, fill=(factor(Age))))+
  geom_bar(stat="identity", position="dodge")+ 
  SepAgePlot+(geom_vline(data=AgeDat, xintercept = columnmeans)+
  theme_classic()
SepAgePlot+labs (x="Year", y="count", title="my graph")

提前感谢您的帮助!

UDPATE:这将是一个示例数据集:

Year    Age Count
1964    31  15
1964    33  23
1964    34  54
1964    35  8
1964    36  44
1964    37  21
1964    38  23
1964    39  26
1964    40  23
1965    30  22
1965    31  23
1965    32  45
1965    33  55
1965    34  23
1965    35  10
1965    36  12
1965    37  16
1965    38  32
1965    39  36
1965    40  13
1966    30  27
1966    31  32
1966    32  19
1966    33  45
1966    34  35
1966    35  60
1966    36  15
1966    37  28
1966    38  56
1966    39  18
1966    40  25
1967    30  36
1967    31  32
1967    32  23
1967    33  9
1967    34  15
1967    35  0
1967    36  5
1967    37  7
1967    38  24
1967    39  31
1967    40  24

每年的平均年龄为:

1964 35.4

1965 35.6

1966 35.0

1967 34.6

我的目标是创建一个按年分组的数据的条形图,用一条线代表每年的平均年龄。

2

您可以使用 dplyr 包中的group_bysummarise函数添加具有每年的平均年龄的列:

AgeDat <- AgeDat %>% group_by(Year) %>% summarise(MeanValue=sum(Age*Count)/sum(Count)) %>% inner_join(AgeDat, .)
AgeDat
    Year Age Count MeanValue
1   1964  30    44  34.64545
2   1964  31    44  34.64545
3   1964  32    46  34.64545
4   1964  33    35  34.64545
5   1964  34    83  34.64545
6   1964  35    70  34.64545
7   1964  36    73  34.64545
8   1964  37    85  34.64545
9   1964  38    31  34.64545
10  1964  39    39  34.64545
11  1965  30   100  34.65485
12  1965  31    19  34.65485

然后,您可以使用geom_vline为每年添加一条垂直线,并使用facet_wrap按年份获取年龄分布:

ggplot(AgeDat) + 
    geom_bar(aes(x=Age, y=Count), stat="identity", position="dodge") + 
    geom_vline(aes(xintercept=MeanValue)) + 
    facet_wrap(~Year, nrow=1) + 
    theme_classic()

enter image description here

本站系公益性非盈利分享网址,本文来自用户投稿,不代表码文网立场,如若转载,请注明出处

(273)
如何使用java将图像转换为qr代码
上一篇
Web服务和ssh之间有什么区别
下一篇

相关推荐

发表评论

登录 后才能评论

评论列表(71条)