如何使用 R 使用.xls文件中的特定行来创建线图?



我想创建一个线图,其中有两个特定的行,第一行作为.xls文件中的x轴。

直到现在,我尝试了ggplot,但我找不到我应该传递给标有问号的地方的内容。

dataset <- read_excel("inflation.xls")
p1 <- ggplot() + geom_line(aes(y = ?, x = ?), data = dataset) 

这是我的预期结果和数据示例。

预期成果

示例数据

在绘制之前,您可能应该尝试将数据转换为整洁的格式(每行都是一个观测值,列是变量(。

在这种情况下,

library(dplyr)
target <- c("Turkey", "Germany")
dataset <- gather(dataset, key = "Year", value = "Inflation", -1) %>% # -1 here to gather all columns except the first 
filter(`Country Name` %in% target) #filter the relevant countries

然后,您的数据集应具有包含每年的"年份"列,以及包含"通货膨胀"值的"通货膨胀"列。

Country Name  Year Inflation
1  Turkey      1960         1
2 Germany      1960         2
3  Turkey      1961         2
4 Germany      1961         3
5  Turkey      1962         3
6 Germany      1962         4

从这里应该很清楚,年份是 x 值,通货膨胀是 Y 值,您希望按国家/地区分组,以便每个国家/地区都有自己的线。

ggplot() +
geom_line(data = dataset, aes(x = Year, y = Inflation, color = Country, group = Country))

最新更新