【问题标题】:plot monthly data with xyplot with R用 xyplot 和 R 绘制每月数据
【发布时间】:2016-11-07 07:49:32
【问题描述】:

我想在 x 轴上用月份绘制这个数据框。

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)

这个例子效果很好。但是当我以完全相同的方式尝试但使用不同的值时,只有 value1 是 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 不显示错误但根本不绘图。

这里可能有什么问题?

非常感谢您的帮助!

【问题讨论】:

  • 您正在混合网格 (lattice/ggplot2) 和基本图形。使用其中一种。

标签: r hmisc


【解决方案1】:

如果您想采用 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()

【讨论】:

  • 哇,完美,这正是我所需要的!非常感谢!!
猜你喜欢
  • 2014-10-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-12-06
  • 1970-01-01
  • 2020-11-04
  • 1970-01-01
  • 2018-07-22
相关资源
最近更新 更多