如何在R中的单个线图上绘制矩阵的列

时间:2014-11-20 10:07:40

标签: r

我创建了一个函数,它从txt文件读取数据以创建表,发生一些数据操作,然后将结果放入矩阵中。这是结果的样本:

          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

我正在试图弄清楚如何在图表上绘制这些数据。我希望将年份作为x轴,将通货膨胀率作为y轴。所以最后我希望每个国家都有一个带有线条(不同颜色)的图表。

这可能吗?

感谢任何帮助,谢谢。

2 个答案:

答案 0 :(得分:3)

尝试

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

或使用ggplot

library(ggplot)
library(reshape2)

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

数据

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

答案 1 :(得分:1)

这可以通过例如使用for循环来完成,但使用函数matplot()可以更有效地作为示例:

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