2014-08-30 89 views
0

我想通过从物理实验室收集的一些数据中绘制3个系列来学习R.我有3个的CSV文件:为什么R在我的图中添加一列?

r.csv:

"Voltage","Current" 
2,133 
4,266 
6,399 
8,532 
10,666 

而且还有两个。我加载它们是这样的:

r <- read.csv("~/Desktop/r.csv") 
rs <- read.csv("~/Desktop/rs.csv") 
rp <- read.csv("~/Desktop/rp.csv") 

然后,我将它们合并成一个矩阵:

data <- cbind(r, rs, rp) 

当我显示data,我得到我虽然只是出现在左边这个额外的列在显示矩阵:

data 
    Voltage Current Voltage Current Voltage Current 
1  2  133  2  270  2 67.4 
2  4  266  4  535  4 134.3 
3  6  399  6  803  6 200.0 
4  8  532  8 1070  8 267.0 
5  10  666  10 1338  10 334.0 

但图表显示一个额外的系列:

matplot(data, type = c("b"), pch=5, col = 1:5, xlab="Voltage (V)", ylab="Current (A)") 

plot

另外,为什么x轴都是错的?数据点位于x = 2,4,6,8和10处,但图表显示它们是1,2,3,4和5.我在这里错过了什么?

回答

3

help(matplot)对于初学者:

matplot(x, y, type = "p", lty = 1:5, lwd = 1, lend = par("lend"), 
     pch = NULL,.... 

说:

x,y: vectors or matrices of data for plotting. The number of rows 
     should match. If one of them are missing, the other is taken 
     as ‘y’ and an ‘x’ vector of ‘1:n’ is used. Missing values 
     (‘NA’s) are allowed. 

所以你只给定的x和y的一个,所以matplot对待你的整个矩阵y1:5矢量在X轴上。 matplot没有足够的精神来实现你的矩阵是X和Y数字的混合。

解决方案是是一样的东西:

matplot(data[,1], data[,-c(1,3,5)],....etc...) 

它得到了X从第一电压列坐标,然后使用负索引见好就收当前列删除所有电压列创建Y矩阵。 data[,c(2,4,6)]也可能工作。

请注意,这只适用于您的三个系列具有所有相同的X值。如果不是这种情况,你想绘制多行,那么我认为你应该看看ggplot2包...

+0

我已经读过,但我真的不明白它。感谢您解决这个问题! – Hassan 2014-08-30 13:58:41

+0

只是一件事:那是什么'-c(..)'?为什么不是'c(..)'? – Hassan 2014-08-30 14:00:33

+0

'-c(1,2,3)'应该与'c(-1,-2,-3)'相同(输入到R来检查),但只需要较少的按键。索引与负数*下降*而不是*选择*项目。试试'(5:12)[ - c(1,3)]'。 – Spacedman 2014-08-30 14:21:41

相关问题