2017-04-04 44 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))