ggplot2 中 geom_bar() 的回归线

Regression line with geom_bar() in ggplot2

我正在尝试将回归线添加到我的条形图中。到目前为止,我向绿色条添加了线性回归,我还可以使用紫色条的数据添加趋势线。我没能做到的是将这个线性模型应用于绿色和紫色条的总和。我得到的最接近的是使用 stat_summary() 添加一条简单的条形总和线。可复制的代码如下。谢谢!

decadeCount <- data.frame(Year=seq(1850, 2010, 10), 
          TS=floor(runif(17, min=0, max=17)), H=floor(runif(17, min=0, max=23)))


decadeCount.m <- melt(decadeCount, id = "Year")
names(decadeCount.m)[2]<-"type"
names(decadeCount.m)[3]<-"count"
decadeCount.m[[1]] <- as.character(decadeCount.m[[1]])
decadeCount.m[[1]] <- paste0(decadeCount.m[[1]], "'s")


ggplot(decadeCount.m[order(decadeCount.m$type,decreasing=T),]) + 
  geom_bar(aes(x = Year, y = count, fill = factor(type, levels=c("H","TS"))),
           stat = "identity",  position = "stack", show.legend = F) +
  geom_smooth(data=decadeCount.m[decadeCount.m$type == "TS",],aes(x = Year, y = count, group=1),
              method = "lm", se= FALSE, color = "firebrick1", size = 2) +
  stat_summary(aes(Year, count),fun.y = sum, geom = "smooth", show.legend = F, group=1) +
  labs(x = "Decade") +
  scale_y_continuous("Count", breaks = seq(5,35,5), limits=c(0,35),
                     expand = expand_scale(mult = c(0.001, 0.05)),
                     sec.axis = dup_axis(name = NULL, labels = NULL)) +
  scale_x_discrete(expand = expand_scale(mult = c(0.05, 0.05))) +
  scale_fill_manual(values=c("#944F9F","#6BBD45"))

您可以直接在ggplot 命令中汇总数据并生成所需的图表。我还使用 geom_col 而不是 geom_bar,因为您使用的是列中的确切值。

ggplot(decadeCount.m[order(decadeCount.m$type,decreasing=T),]) + 
  geom_col(aes(x = Year, y = count, fill = factor(type, levels=c("H","TS"))),
           show.legend = F) +
  geom_smooth(data=decadeCount.m %>% group_by(Year) %>% summarise(count=sum(count)),
              aes(x = Year, y = count, group=1),
              method = "lm", se= FALSE, color = "firebrick1", size = 2) +
  labs(x = "Decade") +
  scale_y_continuous("Count", breaks = seq(5,35,5), limits=c(0,35),
                     expand = expand_scale(mult = c(0.001, 0.05)),
                     sec.axis = dup_axis(name = NULL, labels = NULL)) +
  scale_x_discrete(expand = expand_scale(mult = c(0.05, 0.05))) +
  scale_fill_manual(values=c("#944F9F","#6BBD45"))