绘制具有列的特定平均值的不同颜色的折线图

Plot line graph with different colors of specific average values of a column

我有这样的数据集:

Year  Type Return
1900   A   2
1900   B   4
1901   A   7
1901   A   9
1901   B   6
1901   B   5
1903   B   5
1906   A   5

我有关于两种类型的年度信息和相应的return。 一年可以不止一种,也可以在同一年重复一种。它也可以只有一种类型的年份,以及一些缺失的年份。

我想绘制一个带有颜色的折线图(可能是 ggplot),显示 A 和 B 的 returns 随时间的演变。 (x 轴年份,y 轴 Return)。 当一年中有多个信息时(例如在 1901 年,我们有两个 A),我们应该对 return 求平均值(对于 A:7 和 9 的平均值)。

真实数据库有超过 10k 行的信息。

奖金问题:如果我也可以有一个单独的版本,而不是平均每年的 return,而是对每年的 return 求和(对于 A:7 +9)

谢谢!

你可以试试

library(dplyr)
library(ggplot2)

dummy <- read.table(text = "Year  Type Return
1900   A   2
1900   B   4
1901   A   7
1901   A   9
1901   B   6
1901   B   5
1903   B   5
1906   A   5", header = T)

dummy %>%
  dplyr::group_by(Year, Type) %>%

  dplyr::summarize(m = mean(Return),
            s = sum(Return)) %>%
  ggplot(aes(color = Type)) +
  geom_line(aes(Year, m)) +
  geom_line(aes(Year, s), linetype = 2)

dummy1 <-   dummy %>%
  dplyr::group_by(Year, Type) %>%
  
  dplyr::summarize(m = mean(Return),
                   s = sum(Return))

平均值

dummy1 %>%
  ggplot(aes(color = Type)) +
  geom_line(aes(Year, m))

总和

dummy1 %>%
  ggplot(aes(color = Type)) +
  geom_line(aes(Year, s))

小节

dummy1 %>%
  ggplot(aes(Year, s,fill = Type)) +
  geom_col(stat = "identity")

条形图 + x 轴

dummy1 %>%
  ggplot(aes(Year, s,fill = Type)) +
  geom_col(stat = "identity") +
  scale_x_continuous(breaks = seq(min(dummy1$Year), max(dummy1$Year)))