1

I want to plot this data frame with month on x-axis.

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)

it worked out very well for this example. but when I tried it exactely the same way but with different values, only value1 is plottet and I always get the following errors:

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

I already applied plot.new() and dev.off(). But sometimes I still get these errors or sometimes R doesn't show errors but doesn't plot at all.

What might be the problem here?

Many thanks in advance for your help!

Zheyuan Li
  • 71,365
  • 17
  • 180
  • 248
N_ni
  • 27
  • 4

1 Answers1

0

If you want to go the ggplot2 way, here's how you can morph the data into a long format and plot it using 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

Roman Luštrik
  • 69,533
  • 24
  • 154
  • 197