我有一个如下所示的数据框:
X Y
[1,] 0.0000000 0.2534477
[2,] 0.1020202 0.2532555
[3,] 0.1424242 0.2532177
[4,] 0.2333333 0.2531311
[5,] 0.3848485 0.2529815
[6,] 0.6171717 0.2527504
[7,] 1.0000000 0.2524634
我希望在一张图中打印这两列,但颜色不同。我这样做了
plot(dat1$Y,type="o",col="red")
lines(dat1$X,type="o",col="blue")
UPDATE 1:修改后我正在执行这些命令:
x_val <- seq(0,7,7)
plot(x_val,dat1$Y,type="o",ylim=c(0.2,0.3),col="red")
plot(x_val,dat1$X,type="o",ylim=c(0,1),col="blue")
但我收到错误
Error in xy.coords(x, y, xlabel, ylabel, log) :
'x' and 'y' lengths differ
但是在图表Y中,图表是正确的,但X图表看起来像一条直线而不是Y图。为什么会这样?
答案 0 :(得分:1)
试试这个:
x <- 1:7
y <- dat1$Y
z <- dat1$X
par(mar = c(5, 4, 4, 4) + 0.3)
plot(x, y, type = "o", col = "red", ylab = "dat1$Y")
par(new = TRUE)
plot(x, z, type = "o", col = "blue", axes = FALSE, bty = "n", xlab = "", ylab = "")
axis(side=4, at = pretty(range(z)))
mtext("dat1$X", side=4, line=3)
答案 1 :(得分:0)
为可重现的示例生成一些数字:
set.seed(42)
df <- data.frame(id = 1:7, x = runif(7), y = runif(7))
导致:
id x y
1 1 0.4622928 0.13871017
2 2 0.9400145 0.98889173
3 3 0.9782264 0.94666823
4 4 0.1174874 0.08243756
5 5 0.4749971 0.51421178
6 6 0.5603327 0.39020347
7 7 0.9040314 0.90573813
融化数据以便于绘图:
library(reshape2)
df <- melt(df, id.vars = 'id')
然后拨打ggplot
:
library(ggplot2)
ggplot(df, aes(x = id, y = value, color = variable)) + geom_line()