首页 > 解决方案 > 在同一个ggplot上绘制多个时间序列

问题描述

我一直在尝试使用 ggplot 绘制 2 行图,但它显示以下内容:“美学必须是长度 1 或与数据 (1) 相同:x 和 y”。

这是我正在使用的数据集: unvoting <- read.csv (" https://raw.githubusercontent.com/umbertomig/intro-prob-stat-FGV/master/datasets/unvoting.csv ")

问题是:“检查苏联/后苏联国家和所有其他国家的理想中位数在数据中多年来的变化情况。按年份绘制这些理想中位数。”

这是我到目前为止使用的代码:

pst_svt <- subset(unvoting, svtunion == 1)
othr_cts <- subset(unvoting, svtunion == 0)

y1 <- tapply(othr_cts$idealpoint, othr_cts$Year, median)
y2 <- tapply(pst_svt$idealpoint,pst_svt$Year, median)

ggplot(pst_svt) +
 geom_line(aes(x= Year, y= y1, color="Other Countries")) +
 geom_line(aes(x= Year, y=y2, col="Other Countries")) +
 scale_color_discrete(name="Legend") +
 labs(title="Variation of Median Ideal Points")

标签: rggplot2

解决方案


我会这样做。您可以聚合 Year 和 svtunion。

Soviet_countries <- c("Estonia", "Latvia", "Lithuania", "Belarus", "Moldova", "Ukraine", "Armenia", 
                      "Azerbaijan", "Georgia", "Kazakhstan", "Kyrgyzstan", "Tajikistan", 
                      "Turkmenistan", "Uzbekistan", "Russia") 

library(dplyr)
library(ggplot2)

unvoting <- mutate(unvoting, 
      svtunion=ifelse(CountryName %in% Soviet_countries, "Soviet", "non-Soviet"))

y <- aggregate(idealpoint~Year+svtunion, FUN=median, data=unvoting)

ggplot(y) +
  geom_line(aes(x=Year, y=idealpoint, col=svtunion)) +
  scale_color_discrete(name="Legend") +
  labs(title="Variation of Median Ideal Points")

在此处输入图像描述


推荐阅读