Kane
Kane

Reputation: 924

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

I created a function which reads data from a txt file to create a table, some data manipulation occurs and then the results are put into a matrix. This is a sample of the 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'm trying to figure out how I can plot this data on a graph. I want to have the years as the x - axis and the inflation rate as the y - axis. So in the end I would like one graph with lines (in different colours) for each country.

Is this possible to do?

Any help appreciated, thank you.

Upvotes: 11

Views: 17738

Answers (2)

akrun
akrun

Reputation: 887481

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")))

Upvotes: 9

user2357031
user2357031

Reputation:

This can be done, e.g., using a for-loop, but much more efficiently using the 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)

Upvotes: 1

Related Questions