Paradox
Paradox

Reputation: 2035

Multiple plots with variable color in R ggplot

I would like to plot multiple plots on the same graph in R, and have them color-coded according to a third variable, but I don't know how to do this within one data frame in ggplot2.

So for example my data could look like (made up data):

Time = [1 2 3 4 5]

YData = [10 11  9 10 12]
        [ 5  3  4  6  9]

ColorData = [2.5 2.6 2.7 2.8 2.9]
            [0.1 1.2 2.4 1.6 0.2]

I need to plot "YData[1,] vs Time" with points colored on some color-scale according to ColorData[1,]. Then I need to plot "YData[2,] vs Time" with points on a color-scale according to ColorData[2,]. Both plots would go on the same axes. In practice my matrices will be enormous so I can't plot each thing manually. Any ideas how I could do this?

data example :

dx <- data.frame(Time = c(1, 2, 3 ,4, 5), 
                 YData1 = c(10 ,11  ,9 ,10 ,12),
                 YData2 = c(5  ,3  ,4  ,6  ,9),
                 ColorData1 = c(2.5 ,2.6 ,2.7, 2.8, 2.9),
                 ColorData2 =  c(0.1, 1.2, 2.4, 1.6, 0.2)
                 )

Code without color:

 library(reshape2)
 dx.melted = melt(dx, id = "Time")
 ggplot(data = dx.melted, aes(x = Time, y = value)) + geom_point()

Upvotes: 0

Views: 1618

Answers (1)

agstudy
agstudy

Reputation: 121568

You should reshape your data before plotting. Usually we use the reshape command to put data in the long format. Here I am using a manual method but that it is general to transform your 32 columns data.frame.

dx_reshaped <- data.frame(Time=dx[,1],
                          stack(dx[,(grep('YData',colnames(dx)))]),
                          stack(dx[,(grep('Color',colnames(dx)))]))

Then you plot it like using ggplot2. I am using 2 geoms to distinguish the (the ydata type and the color type).

library(ggplot2)
ggplot(data=dx_reshaped,aes(Time,values)) +
  geom_point(aes(shape=ind),size=4) +
  geom_line(aes(color=values.1,group=ind))

enter image description here

Upvotes: 1

Related Questions