现有barplot上的叠加线

问题描述 投票:0回答:2

我有如下数据:

Year    PostNumber
2008    2
2009    116
2010    511
2011    1578
2012    2429
2013    1724
2014    1026
2015    648
2016    668
2017    546
2018    496
2019    427
2020    115

我想在同一图中绘制条形图和一条线以显示趋势。

我指的是post,这给了我如下图所示的图

enter image description here

代码如下:

p<-ggplot(data=df, aes(x=PostYear, y=PostNumber)) +
  geom_bar(stat="identity", width = 0.4, fill="#0CF7E0")+
  geom_text(aes(label=PostNumber), vjust=0) 

p+scale_x_continuous(breaks = 1:13, labels = df$PostYear) +
  geom_line() + 
  geom_smooth(lty = 2)

PostYear的类别是数字,而PostNumber是整数。

我只在寻找带有标签和趋势线的条形图。

r ggplot2 plot geom-bar
2个回答
0
投票

只需放下geom_line

df  <- read.table(text = "PostYear    PostNumber
2008    2
2009    116
2010    511
2011    1578
2012    2429
2013    1724
2014    1026
2015    648
2016    668
2017    546
2018    496
2019    427
2020    115", header = TRUE)

library(ggplot2)

p<-ggplot(data=df, aes(x=PostYear, y=PostNumber)) +
  geom_bar(stat="identity", width = 0.4, fill="#0CF7E0")+
  geom_text(aes(label=PostNumber), vjust=0) 

p+scale_x_continuous(breaks = 1:13, labels = df$PostYear) +
  geom_smooth(lty = 2)
#> `geom_smooth()` using method = 'loess' and formula 'y ~ x'

“”

reprex package(v0.3.0)在2020-06-07创建


0
投票

我能够使用下面的代码找到所需的解决方案

p<-ggplot(data=df, aes(x=PostYear, y=PostNumber)) +
  geom_bar(stat="identity", width = 0.4, fill="#0CF7E0")+
  geom_text(aes(label=PostNumber), vjust=0) 


p+scale_x_continuous(breaks=seq(2008,2020,1))+
geom_line() + 
  geom_smooth(method = 'gam', inherit.aes = T, lty=2)

这给了我想要的输出如下

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.