ioar
ioar

Reputation: 25

ggplot geom_line(): problems colouring the lines by a factor variable

I am trying to use ggplot to plot number of particles dNon the y axis against it's diameter Dp on the x axis. I have average values per month for a number of years.

My data is preprared in the long format. month, year, and month_yearare factors, and Dp and dNare numeric. I have several years and several diameters (Dp).

 month year   Dp        dN month_year
    1 2006 3.16 4045.1261   1 / 2006
    2 2006 3.16 4447.6436   2 / 2006
    3 2006 3.16 6436.9364   3 / 2006
    4 2006 3.16 5632.1306   4 / 2006
    5 2006 3.16 4840.1949   5 / 2006
    6 2006 3.16 1480.3604   6 / 2006
    7 2006 3.16  928.6990   7 / 2006
    8 2006 3.16 1258.5296   8 / 2006
    9 2006 3.16  725.8546   9 / 2006
   10 2006 3.16  767.1681  10 / 2006
   11 2006 3.16  647.2605  11 / 2006
   12 2006 3.16  449.9188  12 / 2006
    1 2007 3.16  647.4428   1 / 2007
    2 2007 3.16  682.0582   2 / 2007
    3 2007 3.16  614.0303   3 / 2007`

I first did a plot colouring each line by the month_yearvariable:

ggplot(dataplot_m_y) +
  geom_line(aes(Dp, dN, colour = month_year), size=0.5)+
  theme(legend.position = "none")+
  scale_x_log10()

and I obtained this:

enter image description here Every line corresponds to a month, and months are roughly coloured by the same colour (I mean, green colour corresponds approximately to the "Januaries" of all years, etc.). The legend is too long, so I didn't plot it.

Now, I would like to get exactly the same graph but with the same colour per month (and include the legend as well).

This is what I tried:

ggplot(dataplot_m_y) +
  geom_line(aes(Dp, dN, colour = month), size = 0.5)+
  scale_x_log10()

But I got this:

enter image description here

I also tried

ggplot(dataplot_m_y) +
  geom_line(aes(Dp, dN), colour = month, size = 0.5)+
  scale_x_log10()

But I got the following error: "Error in rep(value[[k]], length.out = n) : attempt to replicate an object of type 'closure'"

Could anybody help me solve this? Do I need to arrange the data differently?

Thank you

Upvotes: 0

Views: 1445

Answers (1)

drmariod
drmariod

Reputation: 11762

So the solution should be to define groups for the lines which are actually your month_year but color by month.

ggplot(dataplot_m_y) +
  geom_line(aes(Dp, dN, colour=month, group=month_year), size=0.5)+
  theme(legend.position="none")+
  scale_x_log10()

Upvotes: 1

Related Questions