Skip to content

linetype corruption in ggplot2

3 messages · Rui Barradas, Troels Ring

#
Dear friends - another simple question: the assignment of linetype seems 
to be corrupted in the code below- I would want the solid line
to be the lowest? and also want the legend to be correct. I guess R 
orders the legend names alphabetically and could handle? that but
cannot unnderstand how the lines apparently are switched.

library(ggplot2)

BB <- cbind(c(1,2,3),c(2,4,6),c(3,6,9))
x <- c(2,3,4)
LT <- c("solid","dashed","dotted")

GG <- ggplot()
for (i in 1:3) {
 ? dd <- data.frame(x,BB=BB[i,],LT=LT[i])
 ? GG <- GG + geom_line(data=dd,aes(x=x,y=BB,linetype=LT),size=1)

}
GG+scale_y_continuous(breaks=seq(1,10))

I'm on Windows, R 4.0.5

All best wishes

Troels
#
Hello,

The problem is in the for loop. Every time through it the data argument 
changes and ggplot only evaluates when printing, not when it's 
constructing the object.

It's not a good idea to construct a ggplot object in a loop.

Why don't you put x and BB in a data.frame, reshape it to long format 
and plot all lines in the same instruction?


df1 <- data.frame(x, BB)
names(df1)[2:4] <- paste0("BB", 1:3)

df1_long <- reshape(
   df1, direction = "long",
   varying = names(df1)[2:4],
   v.names = "BB",
   timevar = "LT"
)
df1_long$LT <- LT[df1_long$LT]

ggplot(df1_long, aes(x, BB, linetype = LT)) +
   geom_line() +
   scale_linetype_manual(values = c(solid = "solid", dashed = "dashed", 
dotted = "dotted"))



Hope this helps,

Rui Barradas

?s 13:52 de 01/10/21, Troels Ring escreveu:
#
Thanks a lot, Rui - this works well - although I still fail to see why a 
loop could not do it although your explanation for the problem is well 
taken!

All best
Troels

Den 01-10-2021 kl. 15:21 skrev Rui Barradas: