1

I have a dataframe where the first column is years and consecutive columns are country names with time series data for each country (28). I would like to plot all of them in one go. Here is my code:

 par(mfrow=c(4,7))
    for (i in DP[,2:29]) {
      plot(DP$Year,i,
           ylim=range(c(0, 400)),
           type="p",col="red", xaxt="n", yaxt="n",
           ylab="mortality rate",
           xlab="year",
           pch=16, main=c(colnames(DP[,2:29])))
      axis(side = 1)
      axis(side = 2, seq(from=0, to=400, by=25))
    }

The plot however shows all the country names for every graph. What shall I do?

enter image description here

joran
  • 169,992
  • 32
  • 429
  • 468
  • If the answers do not work with your data, a suggestion: reduce your problem to just 2x2 with very little data, then post the data with `dput(x)`. (My guess is that the answers you get that work with 2 columns/rows will work just as well with 7x7 or 700x700.) References for a more reproducible question: https://stackoverflow.com/questions/5963269, https://stackoverflow.com/help/mcve, and https://stackoverflow.com/tags/r/info. – r2evans Feb 27 '19 at 17:06

1 Answers1

0

You can try putting the country names in a list first and then looping through them.

country_list<-unique(dataset$country)
for (i in seq_along(country_list)){
  plot(DP$Year,i,
       ylim=range(c(0, 400)),
       type="p",col="red", xaxt="n", yaxt="n",
       ylab="mortality rate",
       xlab="year",
       pch=16, main=country_list[i])
  axis(side = 1)
  axis(side = 2, seq(from=0, to=400, by=25))
}

Or you can use ggplot2 and facet_wrap to facet by country.

S. Ash
  • 70
  • 6
  • thanks, but still not working Error in xy.coords(x, y, xlabel, ylabel, log) : 'x' and 'y' lengths differ – Attila Borsos Feb 27 '19 at 16:32
  • Thanks Joran, this was my original code par(mfrow=c(4,7)) for (i in DP[,2:29]) { plot(DP$Year,i, ylim=range(c(0, 400)), type="p",col="red", xaxt="n", yaxt="n", ylab="mortality rate", xlab="year", pch=16) axis(side = 1) axis(side = 2, seq(from=0, to=400, by=25)) } which gave me the plot I wanted but just without titles. – Attila Borsos Feb 27 '19 at 17:05