I have a data frame which looks like this:
我有一个如下所示的数据框:
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
and I want to print these two columns in one graph but with different colors. I did this
我想在一个图表中打印这两列,但颜色不同。我这样做了
plot(dat1$Y,type="o",col="red")
lines(dat1$X,type="o",col="blue")
UPDATE 1: After modification I am executing these commands:
更新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")
but I get error as
但是我得到了错误
Error in xy.coords(x, y, xlabel, ylabel, log) :
'x' and 'y' lengths differ
but in the graph Y plot comes correct but the X plot comes like a straight line and not like Y plot. Why is this happening?
但是在图表中,Y图表是正确的,但X图表看起来像一条直线而不是Y图。为什么会这样?
2 个解决方案
#1
1
Try this:
尝试这个:
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)
#2
0
Generating some numbers for a reproducible example:
为可重现的示例生成一些数字:
set.seed(42)
df <- data.frame(id = 1:7, x = runif(7), y = runif(7))
Resulting in:
导致:
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
Melting data for easy plotting:
融化数据以便于绘图:
library(reshape2)
df <- melt(df, id.vars = 'id')
Then call ggplot
:
然后调用ggplot:
library(ggplot2)
ggplot(df, aes(x = id, y = value, color = variable)) + geom_line()
#1
1
Try this:
尝试这个:
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)
#2
0
Generating some numbers for a reproducible example:
为可重现的示例生成一些数字:
set.seed(42)
df <- data.frame(id = 1:7, x = runif(7), y = runif(7))
Resulting in:
导致:
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
Melting data for easy plotting:
融化数据以便于绘图:
library(reshape2)
df <- melt(df, id.vars = 'id')
Then call ggplot
:
然后调用ggplot:
library(ggplot2)
ggplot(df, aes(x = id, y = value, color = variable)) + geom_line()