How to plot columns of a matrix on one line graph in R

I created a function that reads data from a txt file to create a table, some data manipulation happens, and then the results are put into a matrix. This is a sample result:

          Canada     France       Germany      Italy        Japan        
1973 0.107843137 0.13583815  0.0684713376 0.19417476  0.231732777
1974 0.108407080 0.11704835  0.0596125186 0.17073171  0.116949153
1975 0.075848303 0.09567198  0.0436005626 0.16666667  0.095599393
1976 0.077922078 0.09563410  0.0363881402 0.19345238  0.081717452
1977 0.089500861 0.09108159  0.0273081925 0.12468828  0.042253521

      

I am trying to figure out how I can plot this data in a graph. I want years to be the x-axis and the inflation rate as the y-axis. So in the end I need one line chart (in different colors) for each country.

Can this be done?

Any help is appreciated, thanks.

+3


source to share


2 answers


Try

matplot(rownames(m1), m1, type='l', xlab='Years', ylab='rate', col=1:5)
legend('bottomright', inset=.05, legend=colnames(m1), 
                            pch=1, horiz=TRUE, col=1:5)

      

enter image description here

or using ggplot



library(ggplot)
library(reshape2)

ggplot(melt(m1), aes(x=Var1, y=value, col=Var2))+
                                          geom_line()

      

data

m1 <- structure(c(0.107843137, 0.10840708, 0.075848303, 0.077922078, 
0.089500861, 0.13583815, 0.11704835, 0.09567198, 0.0956341, 0.09108159, 
0.0684713376, 0.0596125186, 0.0436005626, 0.0363881402, 0.0273081925, 
0.19417476, 0.17073171, 0.16666667, 0.19345238, 0.12468828, 0.231732777, 
0.116949153, 0.095599393, 0.081717452, 0.042253521), .Dim = c(5L, 
5L), .Dimnames = list(c("1973", "1974", "1975", "1976", "1977"
), c("Canada", "France", "Germany", "Italy", "Japan")))

      

+3


source


This can be done, for example, using a for-loop, but much more efficiently using a function matplot()

As an example:



# d is the data frame holding your example data.
matplot(d, type="l", ylim=c(0,0.3))

# You can change the appearance of the plot with usual graphical parameters
matplot(d, type="l", ylim=c(0,0.3), lwd=4, col=1:5, lty=1)

      

+1


source







All Articles