Home > Software engineering >  R, ggplot2 multiple geometries?
R, ggplot2 multiple geometries?

Time:09-18

I would like to make a plot with 2 different geometries each representing different data. I have three variables; Time (x), Temperature (y) and Station. I would like to represent some stations as geom_smooth and others as geom_line. Is there any way to tell them to represent only some values?

This is my code:

ggplot(data=StationsData,
   mapping=aes(x=Time, y=Temp, colour=Station))  
geom_smooth() 
scale_color_brewer(palette = "Set1") 
labs(x="Time (Months)", y="Temperature (ºC)", title= "Temperature")

Thanks for your time.

CodePudding user response:

Yes you can. Just make different subsets of your data. Here an example:

library(tidyverse)    
# Data in wide format
    df_wide <- data.frame(
    Horizons = seq(1,10,1),
    Country1 = c(2.5, 2.3, 2.2, 2.2, 2.1, 2.0, 1.7, 1.8, 1.7, 1.6),
    Country2 = c(3.5, 3.3, 3.2, 3.2, 3.1, 3.0, 3.7, 3.8, 3.7, 3.6),
    Country3 = c(1.5, 1.3, 1.2, 1.2, 1.1, 1.0, 0.7, 0.8, 0.7, 0.6)
    )

# Convert to long format
    df_long <- df_wide %>%
      gather(key = "variable", value = "value", -Horizons)

ggplot(subset(df_long, variable != 'Country1'), aes(x = Horizons, y = value))   
  geom_line(aes(colour = variable, group = variable))  
  geom_line(data = subset(df_long, variable == 'Country1'), 
            size = 3, linetype = 'dashed', color = 'blue')  
  theme_bw() 

Notice how country 1 is different. You could use any geom. You like. I hope this helps :)

CodePudding user response:

I found a solution, quite easy.

library("scales")

ggplot() 
   geom_smooth(data=Colorado, mapping=aes(x=Time, y=Temp, color="Logger")) 
   geom_point(data=Colorado2, mapping=aes(x=Time, y=Temp, color="Termometer")) 
   labs(x="Time (Months)", y="Temperature (ºC)", title= "Temperatures Colorado")

Thanks to all for the coments.

  • Related