r - Ordering a Data Frame By 2 Parameters, Then Plotting -
i have data frame gdp values 12 south american countries on ~40 years. snippet of frame follows:
168 chile 1244.1799 1972 169 chile 4076.3207 1994 170 chile 3474.7172 1992 171 chile 2928.1562 1991 172 chile 6143.7276 2004 173 colombia 882.5687 1976 174 colombia 1094.8795 1977 175 colombia 5403.4557 2008 176 colombia 2376.8022 2002 177 colombia 2047.9784 1993
1) want order data frame country. first ~40 values should pertain argentina, next ~40 bolivia, etc.
2) within each country grouping, want order year. first 3 rows should pertain argentina 2012, argentina 2011, argentina 2010, etc.
i can grab data each country individually using subset()
, , order order()
. surely don't have every country , use rbind()
? how do in 1 foul swoop?
3) once have final product, i'd create 12 small, individual line graphs stacked vertically, each pertaining different country, shows trend of country's gdp on ~40 years. how create such plot?
i'm sure find info on 3rd question myself, but, well, don't know such graph called in first place..
here solution ggplot2
. assuming data in df
:
library(ggplot2) df$year.as.date <- as.date(paste0(df$year, "-01-01")) # convert year date ggplot(df, aes(x=year.as.date, y=gdp)) + geom_line() + facet_grid(country ~ .)
you don't need sort year , country, ggplot
handle you. here data (clearly, using 5 countries , 12 years, work data). also, show how sort 2 columns on third line:
countries <- c("arg", "bra", "chi", "per", "uru") df <- data.frame(country=rep(countries, 12), year=rep(2001:2012, each=5), gdp=runif(60)) df <- df[order(df$country, df$year),] # <- sort here df$gdp <- df$gdp + 1:12 / 2
Comments
Post a Comment