[英]Multi Line Graph in R
我有一個.csv文件,其中提供了過去50年中每個國家/地區的平均預期壽命。 我正在嘗試創建按國家/地區划分的預期壽命圖表,x軸為1960-2011年,y軸為平均壽命。 我只想繪制前十個國家/地區,每個國家都有自己的路線。 我研究了各種可能的方法來繪制我的數據的多線圖,在我看來,用數據格式化的方式是不可能的。 我的問題是:
我能夠在Excel中創建所需的圖形 這正是我想在R中做的。
這是lexp.csv文件的鏈接。 https://drive.google.com/file/d/0BwsBIUlCf0Z3QVgtVGt4ampVcmM/view?usp=sharing
您是正確的,數據將從重組中受益。 這是一個“從寬到長”的問題, 即最好有3列:“國家/地區”,“年份”和“年齡”。
您可以使用tidyr
軟件包重新格式化數據,使用tidyr
軟件包處理數據,並使用dplyr
進行ggplot2
。 因此,假設您已將CSV讀入R並具有一個名為lexp
的數據框,則可以嘗試如下操作:
library(dplyr)
library(tidyr)
library(ggplot2)
lexp %>%
# reformat from wide to long
gather(Year, Age, -Country, convert = TRUE) %>%
# select most recent year
filter(Year == max(Year)) %>%
# sort by decreasing age
arrange(desc(Age)) %>%
# take the top 10 countries
slice(1:10) %>%
select(Country) %>%
# join back to the original data
inner_join(lexp) %>%
# reformat again from wide to long
gather(Year, Age, -Country, convert = TRUE) %>%
# and plot the graph
ggplot(aes(Year, Age)) + geom_line(aes(color = Country, group = Country)) +
theme_dark() + theme(axis.text.x = element_text(angle = 90)) +
labs(title = "Life Expectancy") +
scale_color_brewer(palette = "Set3")
library("reshape2")
library("ggplot2")
test_data_long <- melt(df, id="Country") # convert to long format
testdata<-test_data_long[complete.cases(test_data_long),]
ggplot(data=testdata,
aes(x=variable, y=value)) +
geom_line(aes(color = Country, group = Country))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.