r - 在同一个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")
解决方案
我会这样做。您可以聚合 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")
推荐阅读
- python - Python 执行 ssh 命令(SSH 服务器仅用于远程端口转发)并捕获输出
- c++ - C ++ Gtest如何将参数传递给类夹具?
- r - 按组合并两个因子时重新计算新的加权平均值,并保留原始数据
- c++ - 无法连接到两台不同机器上的 localhost
- vba - 我无法检索网页上的信息
- android - Android Livedata 存储库单元测试问题
- image - 如何在文件对象的资产文件夹中加载图像?我收到一个错误“没有这样的文件或目录,errno = 2”
- c++ - CUDA 代码可以在 Linux 上编译,但不能在 Windows 上编译(Visual Studio 2012)
- r - 为不包括结果列的每个组合附加缺失的日期
- p5.js - 我的一个变量被无缘无故地改变了