[R] linetype corruption in ggplot2

Rui Barradas ru|pb@rr@d@@ @end|ng |rom @@po@pt
Fri Oct 1 15:21:55 CEST 2021


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:
> 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
> 
> ______________________________________________
> R-help using r-project.org mailing list -- To UNSUBSCRIBE and more, see
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide 
> http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.



More information about the R-help mailing list