如何使用带有 R 的 .xls 文件中的特定行来创建线图?
How to create a line plot by using specific rows from a .xls file with R?
我想创建一个线图,其中包含两个特定的行,第一行作为 .xls 文件中的 x 轴。
直到现在,我尝试了 ggplot,但我找不到我应该将什么传递给标有问号的地方。
dataset <- read_excel("inflation.xls")
p1 <- ggplot() + geom_line(aes(y = ?, x = ?), data = dataset)
这是我的数据的预期结果和样本。
Expected Result
Sample Data
在绘图之前,您可能应该尝试将数据转换为 tidy format(每行是一个观察值,每列是变量)。
在这种情况下,
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
然后您的数据集应该有一个年份列和一个包含 inflation 值的 Inflation 列。
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
从这里应该清楚 Year 是 x 值,Inflation 是 Y 值,您想按国家/地区分组,以便每个国家/地区都有自己的行。
ggplot() +
geom_line(data = dataset, aes(x = Year, y = Inflation, color = Country, group = Country))
我想创建一个线图,其中包含两个特定的行,第一行作为 .xls 文件中的 x 轴。
直到现在,我尝试了 ggplot,但我找不到我应该将什么传递给标有问号的地方。
dataset <- read_excel("inflation.xls")
p1 <- ggplot() + geom_line(aes(y = ?, x = ?), data = dataset)
这是我的数据的预期结果和样本。
Expected Result
Sample Data
在绘图之前,您可能应该尝试将数据转换为 tidy format(每行是一个观察值,每列是变量)。
在这种情况下,
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
然后您的数据集应该有一个年份列和一个包含 inflation 值的 Inflation 列。
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
从这里应该清楚 Year 是 x 值,Inflation 是 Y 值,您想按国家/地区分组,以便每个国家/地区都有自己的行。
ggplot() +
geom_line(data = dataset, aes(x = Year, y = Inflation, color = Country, group = Country))