Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

plotting melted variables in manually defined order ggplot

Tags:

r

ggplot2

I have a matrix with six columns. I would like to plot each column separately.

First I create the matrix:

a<-replicate(6,rnorm(100))
colnames(a)<-c("one", "two", "three", "four", "five","six")

then I melt() the variables:

b<-melt(a, id.vars=1:6)
    colnames(b)<-c("c","variable","value")

Now I would like to plot these variables:

ggplot(b,aes(x = c, y = value, colour = variable, linetype = variable,size = variable)) + 
     geom_line() + 
     scale_x_continuous(breaks=seq(0,100,5)) +
     scale_colour_manual(values=c("blue1", "blue1","blue1","blue1","blue1","blue1")) + 
     scale_linetype_manual(values = c(0,0,1,0,0,0)) + 
     scale_size_manual(values = c(0.2,0.2,0.2,0.2,0.2,0.2)) + 
     xlab("\nT") + 
     ylab("O\n") +
     theme_bw()

However, instead of getting the variables plotted in order of "one", "two", "three" etc as specified, the order is mixed up to: five four one six three two. How can have the variables plotted in the order of the column names specified?

like image 405
user1723765 Avatar asked Jun 07 '26 18:06

user1723765


1 Answers

b$variable will show you the factor levels for that column. That's the order ggplot is taking. You can change the levels like this - b$variable <- factor(b$variable, levels =c("one","two","three","four","five","six"))

like image 165
TheComeOnMan Avatar answered Jun 09 '26 07:06

TheComeOnMan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!