2016-11-07 113 views
1

我想在x軸上繪製這個數據框。用xyplot繪製月度數據R

month value1 value2 value3 value4 
1 Okt 19.5505 19.6145 19.5925 19.3710 
2 Nov 21.8750 21.7815 21.7995 20.5445 
3 Dez 25.4335 25.2230 25.2800 22.7500 

t = read.csv("Mappe1.csv", header = TRUE, sep=";", dec = ".", fill = TRUE, comment.char = "") 

t$m <- factor(t$m, levels = c("Okt", "Nov", "Dez")) 

library(Hmisc) 

xyplot(t$value1~t$m, type = "l", col = "red", ylab="values") 
lines(t$value2~t$m, type = "l", col = "cyan") 
lines(t$value3~t$m, type = "l", col = "purple") 
lines(t$value4~t$m, type = "l", col = "black", lwd = 2) 
legend("topleft", legend=c("value1", "value2", "value3", "value4"), 
    col=c("red", "cyan", "purple", "black"), lty=1:1, cex=0.8) 

它對這個例子很好。但是當我試圖exactely方式相同,但具有不同的值,只有數值1 plottet,我總是得到以下錯誤:

Error in plot.xy(xy.coords(x, y), type = type, ...) : 
    plot.new has not been called yet 
Error in strwidth(legend, units = "user", cex = cex, font = text.font) : 
    plot.new has not been called yet 

我已經申請plot.new()和dev.off()。但有時我仍然會得到這些錯誤,或者有時候R不會顯示錯誤,但根本不會顯示。

這裏有什麼問題?

非常感謝您的幫助!

+0

你混合網格(格子/ GGPLOT2)和鹼的圖形。使用一個或另一個。 –

回答

0

如果您想要採用ggplot2方式,請按照以下步驟將數據轉換爲長格式並使用ggplot2進行繪製。

t <- read.table(text = "month value1 value2 value3 value4 
1 Okt 19.5505 19.6145 19.5925 19.3710 
2 Nov 21.8750 21.7815 21.7995 20.5445 
3 Dez 25.4335 25.2230 25.2800 22.7500", header = TRUE) 

t$month <- factor(t$m, levels = c("Okt", "Nov", "Dez")) 

library(tidyr) 

# "melt" the data into a long format 
# -month tells the function to "melt" everything but month 
xy <- gather(t, key = variable, value = value, -month) 

library(ggplot2) 

# for some reason you need to specify group and color to make things work 
ggplot(xy, aes(x = month, y = value, group = variable, color = variable)) + 
    theme_bw() + 
    geom_line() 

enter image description here

+0

哇完美,這正是我需要的!非常感謝你!! –