簡體   English   中英

R中的多線圖

[英]Multi Line Graph in R

我有一個.csv文件,其中提供了過去50年中每個國家/地區的平均預期壽命。 我正在嘗試創建按國家/地區划分的預期壽命圖表,x軸為1960-2011年,y軸為平均壽命。 我只想繪制前十個國家/地區,每個國家都有自己的路線。 我研究了各種可能的方法來繪制我的數據的多線圖,在我看來,用數據格式化的方式是不可能的。 我的問題是:

  1. 給定其組織方式,是否可以使用此數據創建所需的圖形?
  2. 如果必須重組數據,該怎么做? R中是否有功能可以更好地組織數據?

我能夠在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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM