r group maddison数据按大陆和年份分列

时间:2018-02-07 12:35:26

标签: r ggplot2

我在时间和空间上下载了gdp的maddison数据。我想要一个简单的图表,它总结了从2003年到第1年的每个大陆的gdp(这是数据的结尾)。

我写了

install.packages("maddison")
library(maddison)
install.packages("ggplot2")
library(ggplot2)

str(maddison)

maddi <- maddison

library(lubridate)

maddi$year <- as.character(maddi$year)
maddi$year2 <- substr(maddi$year, start = 1, stop = 4)
maddi$year2 <- as.numeric(maddi$year2)

table(maddi$continent)
table(maddi$region)


maddi2 <- maddi[ which(maddi$continent == 'Asia'| maddi$continent == 'Europe'| maddi$continent == 'Africa'), ]
maddi3 <- maddi2 [!(maddi2$region == "Southern Europe" | maddi2$region == "Northern Europe"), ]

library('stringr')

maddi3$continent <- ifelse(maddi3$continent == "Europe" & maddi3$region == "Eastern Europe", maddi3$continent == "Eastern Europe", maddi3$continent) 
maddi3$continent <- str_replace_all(maddi3$continent, 'FALSE', 'Eastern Europe')
maddi3$continent <- str_replace_all(maddi3$continent, 'Europe', 'Western Europe')

table(maddi3$continent)

maddi4 <- maddi3 [!(maddi3$country == "Japan"), ]

library(dplyr)

maddi4 %>% 
  group_by(continent) %>% 
  ggplot(maddi4, aes(x=year2, y=gdp_pc, color=continent)) +
  geom_line(size=1) +
  xlab("") +
  ylab("Total GDP ($ trillions)") +
  theme_minimal(base_size = 12)

最终的图表虽然不是我想要的。如何获得我能用excel创建的简单图表? enter image description here

我也很乐意为此写出更好,更优雅的代码。感谢。

1 个答案:

答案 0 :(得分:0)

此代码将为您提供正确的图表;)

maddi4 %>% 
  group_by(continent, year2) %>% 
  summarise(mean = mean(gdp_pc, na.rm = TRUE)) %>%
  drop_na() %>% 
  ggplot(aes(x=year2, y=mean, color=continent)) +
  geom_line(size=1) +
  xlab("") +
  ylab("Total GDP ($ trillions)") +
  theme_minimal(base_size = 12)

enter image description here