I am trying to display multiple plots at once using ggplot2 in R.
There are more than 200 cities in the data but I created just a random sample data as follows:
#sample data
df <- data.frame(
city = c('paris', 'tokyo', 'seoul', 'shanghai', 'berlin', 'rome')
, week = c(41,42)
, type = c('A','B','C')
, count = sample(1:100, 24, replace = F)
)
df <- data.table(df)
df[, .(count=sum(count)), by =.(city,type, week)]
In the original data, there are more than 200 cities, but I just created random data for this.
I would like to extract top 10 cities based on number of counts, put the top 10 cities into a list, and loop it to automatically plot out on viewer.
I could use facet_grid option, but for this purpose, I would need to figure this way.
This article has helped me to shape so far, but It's not working because I am not counting numeric values but factors to loop the graphs.
# function
plotCities <- function(cityName){
df <- df[city == cityName,]
ggplot(df,
aes(x = as.factor(week), y = count,
color = as.factor(week), group = as.factor(week))) +
scale_y_continuous(labels = comma) +
geom_point() +
geom_line() +
labs(title = "cities monthly counts",
x = "month",
y = "counts")+
theme(axis.text.x=element_text(angle=90,hjust=1,vjust=1))
}
plotCities("paris")
This won't create nice graph but that doesn't matter at this point as the objective here is to plot multiple at display.
for(cityName in df$city) {
plotCities(cityName)
}
Thought this would work but that didn't create the list I want to... so a fail.
My next attempt was:
p <- list()
for(i in 1:length(df$city)){
cityName = df2[i, 1]
p[[i]] = plotCities(cityName)
}
which doesn't work probably because the city value is factor?
Please share me some tips!