2017-04-04 32 views
0

我有一个.csv文件,显示过去50年来各国的平均预期寿命。我试图创建一个按国家预期寿命的图表,其中1960 - 2011年为x轴,y轴为平均预期寿命。我只想绘制排名前十的国家,每个国家都有自己的路线。 我已经研究过每一种可能的方式来绘制我有的数据的多线图,在我看来,数据格式化的方式是不可能的。我的问题是:R中的多线图

  1. 是否可以使用此数据创建所需图形?
  2. 如果数据需要重新构造,应该怎么做? R中有更好的组织数据的函数吗?

我能够在Excel中创建HERE所需的图形这是我想R.

做的正是这里的lexp.csv文件的链接。 https://drive.google.com/file/d/0BwsBIUlCf0Z3QVgtVGt4ampVcmM/view?usp=sharing

+0

你如何定义“前10名“?最近一年的最高平均值? – neilfws

+1

'库(tidyverse); gsheet :: gsheet2tbl('https://docs.google.com/spreadsheets/d/1K5CKUaiUyhTy9YFjDCqLzmKgRf_DO2Ycy0Wbv95KwC4/edit?usp=sharing')%>%top_n(10,\'2011 \')%>%gather(Year,\ (预期寿命), - 国家,转换= TRUE)%>%ggplot(aes(Year,\'Life Expectancy \',color = Country))+ geom_line()' – alistaire

+0

这是我的宠物,预期“是多余的。预期寿命是一个平均值。 (这是统计期望值。) –

回答

2

你是对的,数据将从重组中受益。这是一个“广泛到长期”的问题最好有3列:国家,年份和年龄。

您可以使用它使用dplyr包和阴谋使用ggplot2tidyr包,过程数据的格式。因此,假设您已经阅读了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") 

结果: enter image description here

+2

虽然看起来与图像相同,但如果您通过在“gather”中指定“convert = TRUE”将“Year”转换为整数,则看起来_better_,以便x轴呈现正常。 – alistaire

0
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))