在同一ggplot上绘制多个时间序列

时间:2020-05-14 03:48:44

标签: r ggplot2

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

这是我正在使用的数据集:取消投票<-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")

2 个答案:

答案 0 :(得分:3)

我会这样做。您可以汇总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")

enter image description here

答案 1 :(得分:0)

下面可以做到这一点:

unvoting$svtunion<-ifelse(grepl("Russia|Georgia|Ukraine|Moldova|Belarus|Armenia|Azerbaijan| Kazakhstan|Uzbekistan|Turkmenistan|Kyrgyzstan|Tajikistan", unvoting$CountryName), 1, 0)

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)


y1<-y1 %>% as.data.frame() %>% mutate(Year = rownames(y1),type = "y1")
y2<-y2 %>% as.data.frame() %>% mutate(Year = rownames(y2),type = "y2")

x<-rbindlist(list(y1,y2), use.names = T, fill = T)
colnames(x)[1]<-"median"

ggplot(x) +
  geom_line(aes(x= Year, y= median,group = type ,color = type)) +
  labs(title="Variation of Median Ideal Points")

enter image description here