将绘图分成R中的2个水平部分

时间:2014-06-27 13:20:11

标签: r plot

我想根据以下数据在R中制作一个情节:

1.txt 3.103 12
2.txt 3.020 11
3.txt 2.929 10
4.txt 3.020 11
5.txt 2.929 10
a.txt 4.254 39
b.txt 4.228 38
c.txt 4.175 36
d.txt 4.175 36
e.txt 4.175 36

我想要一个变量来存储第二列的值和第三列的值。唯一的问题是它们的线条相距太远,如果我设置ylim=c(3,40),第一行几乎是直的,这在我的情况下是不正确的。

我该如何解决这个问题?

我想的可能是用水平线分割图表,在它下面为第二列分配正确的值,在第三列之上有正确的值,只有我不知道如何做到这一点。这是一个好方法吗?

这是我到目前为止的代码:

plot(a,type="o",col="blue",pch=0,lty=2,xaxt="n",ylim=c(3,40))
lines(b,type="o",col="green",pch=5,lty=3)
axis(side=1,at=seq(1,45,1),cex.axis=0.5,las=1)

这是情节: enter image description here

2 个答案:

答案 0 :(得分:3)

以下是使用ggplot方面的解决方案。 df定义为另一个答案。

colnames(df) <- c("id","y1","y2")
df$x         <- 1:nrow(df)
library(reshape2)   # for melt(...)
library(ggplot2)
gg <- melt(df,id="x", measure.vars=c("y1","y2"))
ggplot(gg, aes(x=x,y=value,color=variable)) +
  geom_point(shape=1, size=4)+
  geom_line(linetype="dashed")+
  facet_grid(variable~., scales="free_y")

这具有显示y1和y2的实际值的(可能是次要的)优势。

答案 1 :(得分:2)

你可以在绘图之前normalise

#reproducible data
df <- read.table(text="1.txt 3.103 12
2.txt 3.020 11
3.txt 2.929 10
4.txt 3.020 11
5.txt 2.929 10
a.txt 4.254 39
b.txt 4.228 38
c.txt 4.175 36
d.txt 4.175 36
e.txt 4.175 36")

#normalise 0-1 range
#(m - min(m))/(max(m)-min(m))
df$V2 <- (df$V2-min(df$V2))/(max(df$V2)-min(df$V2))
df$V3 <- (df$V3-min(df$V3))/(max(df$V3)-min(df$V3))

#plot
plot(df$V2,type="o",col="blue",pch=0,lty=2,xaxt="n")
lines(df$V3,type="o",col="green",pch=5,lty=3)
axis(side=1,at=seq(1,45,1),cex.axis=0.5,las=1)

enter image description here