[英]Line plot of multiple variables in R
我有以下格式的輸入數據。
x y z
0 2.2 4.5
5 3.8 6.8
10 4.6 9.3
15 7.6 10.5
我如何在R中繪制像excel這樣的xy散點圖?
1)在此處使用“水平”或“寬” data.frame,稱為df
df <- data.frame(x = c(0, 5, 10, 15), y = c(2.2, 3.8, 4.6, 7.6), z = c(4.5, 6.8, 9.3, 10.5))
ggplot(df, aes(x)) +
geom_line(aes(y = y, colour = "y")) +
geom_line(aes(y = z, colour = "z"))
2)使用晶格
require(lattice)
xyplot(x ~ y + z, data=df, type = c('l','l'), col = c("blue", "red"), auto.key=T)
3)將原始df轉換為“長” data.frame。 這就是通常在ggplot2
處理數據的ggplot2
require("reshape")
require("ggplot2")
mdf <- melt(df, id="x") # convert to long format
ggplot(mdf, aes(x=x, y=value, colour=variable)) +
geom_line() +
theme_bw()
4)使用matplot()我沒有真正研究過這個選項,但是這里有一個例子。
matplot(df$x, df[,2:3], type = "b", pch=19 ,col = 1:2)
如果您可以說自己在這里遇到的困難,可能會有所幫助。 在R中這確實是微不足道的。您應該查看?plot和?lines的文檔。 對於簡單的概述, Quick R很棒。 這是代碼:
windows()
plot(x, y, type="l", lwd=2, col="blue", ylim=c(0, 12), xaxs="i", yaxs="i")
lines(x,z, lwd=2, col="red")
legend("topleft", legend=c("y","z"), lwd=c(2,2), col=c("blue","red"))
請注意,如果您使用的是Mac,則需要quartz()
而不是windows()
。 這是情節:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.