问题描述
我有一个名为 foo.csv
的逗号分隔文件,其中包含以下数据:
I have a comma separated file named foo.csv
containing the following data:
scale, serial, spawn, for, worker
5, 0.000178, 0.000288, 0.000292, 0.000300
10, 0.156986, 0.297926, 0.064509, 0.066297
12, 2.658998, 6.059502, 0.912733, 0.923606
15, 188.023411, 719.463264, 164.111459, 161.687982
我基本上有两个问题:
1) 如何绘制第一列(x 轴)与第二列(y 轴)?我正在尝试这个(从阅读这个网站):
1) How do I plot the first column (x-axis) versus the second column (y-axis)? I'm trying this (from reading this site):
data <- read.table("foo.csv", header=T,sep=",")
attach(data)
scale <- data[1]
serial <- data[2]
plot(scale,serial)
但是我又收到了这个错误:
But I get this error back:
Error in stripchart.default(x1, ...) : invalid plotting method
知道我做错了什么吗?快速谷歌搜索发现其他人有同样的问题但没有相关的答案.更新:事实证明,如果我跳过中间的两个赋值语句,它可以正常工作.知道这是为什么吗?
Any idea what I'm doing wrong? A quick Google search reveals someone else with the same problem but no relevant answer. UPDATE: It turns out it works fine if I skip the two assignment statements in the middle. Any idea why this is?
在第一个问题之后很容易出现第二个问题:
The second question follows pretty easily after the first:
2) 如何绘制第一列(x 轴)与 y 轴上的所有其他列?我认为一旦我解决了我遇到的第一个问题,这很容易,但我对 R 有点陌生,所以我仍然在围绕它.
2) How do I plot the first column (x-axis) versus all the other columns on the y-axis? I presume it's pretty easy once I get around the first problem I'm running into, but am just a bit new to R so I'm still wrapping my head around it.
推荐答案
你不需要这两行:
scale <- data[1]
serial <- data[2]
因为已经从 read.table
的标题中设置了比例和序列.
as scale and serial are already set from the headers in the read.table
.
还有 scale <- data[1]
从 data.frame
data[1]
1 5
2 10
3 12
4 15
而 read.table
中的 scale
是一个向量
whereas scale
from the read.table
is a vector
5 10 12 15
和 plot(scale, serial)
函数需要向量而不是 data.frame,所以你只需要做
and the plot(scale, serial)
function expects vector rather than a data.frame, so you just need to do
plot(scale, serial)
在 y 轴上绘制其他数据列的一种方法:
One approach to plotting the other columns of data on the y-axis:
plot(scale,serial, ylab="")
par(new=TRUE)
plot(scale,spawn,axes=F, ylab="", type="b")
par(new=TRUE)
plot(scale,for., axes=F, ylab="", type="b")
par(new=TRUE)
plot(scale,worker,axes=F, ylab="", type="b")
可能有更好的方法来做到这一点,但这超出了我目前的 R 知识......
There are probably better ways of doing this, but that is beyond my current R knowledge....
这篇关于在 R 中绘制简单数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!