Search code examples
rcomparison

Use of matplot type="b" for comparison


I am trying to create a graph of comparison between three categories and how they have varied their values over time. However, I realize that I am systematically doing something wrong since instead of generating 3 lines representing the 3 categories, I only generate 2 lines. I have tried different variations with the values however, I realize that I need to change something in matplot

Could you give me some insight about how I could correct it?

us1 <- data.frame(category = factor(c("Category1", "Category1", "Category2", 
                                      "Category2", "Category3", "Category3")), 
                  time = factor(c("1975", "2000", "1975", "2000", "1975", "2000"), 
                                      levels=c("1975","2000")), 
                  values = c(529, 233, 229, 246, 40, 47))
    
us1mat <- matrix(us1$values,
                 nrow = 3,
                 byrow=TRUE,
                 dimnames = list(c("Category1","Category2", "Category3"), 
                                 c("1975", "2000"))
          )


usfm_col <- c("blue", "black", "red")

par(cex=1.2, cex.axis=1.1)
matplot(us1mat, type = "b", lty = 1, pch = 19, col = usfm_col,
        cex = 1.5, lwd = 3, las = 1, bty = "n", xaxt = "n",
        xlim = c(0.7, 2.2), ylim = c(0,1000), ylab = "",
        main = "Changes during 1975-2000", yaxt = "n")
axis(2, at = axTicks(2), labels = sprintf("$%s", axTicks(2)),
     las = 1, cex.axis = 0.8, col = NA, line = -0.5)
grid(NA, NULL, lty = 3, lwd = 1, col = "#000000")
abline(v = c(1,2), lty = 3, lwd = 1, col = "#000000")
mtext("1975", side = 1, at = 1)
mtext("2000", side = 1, at = 2)

Solution

  • try to transpose your data matrix:

    matplot(t(us1mat), type="b", lty=1, pch=19, col=usfm_col,
        cex=1.5, lwd=3, las=1, bty="n", xaxt="n",
        xlim=c(0.7, 2.2), ylim=c(0,1000), ylab="",
        main="Changes during 1975-2000", yaxt="n")
    

    Hope it works!