Home > Mobile >  How can geom_path and geom_point colors be changed separately so they are reflected in the legend?
How can geom_path and geom_point colors be changed separately so they are reflected in the legend?

Time:02-01

If I have two datasets, and want to plot them as points with a line through them. I can very simply do that with code like this.

library(ggplot2)

xdata = c(1,2,3,4,5,6)
ydata = xdata^2
ydata2 = 2^xdata
xydata = data.frame(xdata,ydata)

ggplot(xydata)  
  geom_path(aes(x=xdata,y=ydata,color="x^2"),size=1)  
  geom_point(aes(x=xdata,y=ydata,color="x^2"),size=2)  
  geom_path(aes(x=xdata,y=ydata2,color="2^x"),size=1)  
  geom_point(aes(x=xdata,y=ydata2,color="2^x"),size=2)

Which results in enter image description here

CodePudding user response:

Legends in ggplot2 reflect how visual qualities (e.g. color, linetype) are mapped to data, so its easier if there is data that can answer the question "what color should this be?", for example. For this reason, it works better to have all the "y" data in one long column, and have another column that explains which group each value belongs to so that color and linetype can be mapped to that column.

library(ggplot2)
library(dplyr)
#> 
#> Attaching package: 'dplyr'
#> The following objects are masked from 'package:stats':
#> 
#>     filter, lag
#> The following objects are masked from 'package:base':
#> 
#>     intersect, setdiff, setequal, union
xdata = c(1,2,3,4,5,6)

df <- data.frame(x = rep(xdata, 2),
                 y = c(xdata^2, 2^xdata),
                 func = factor(rep(c("x^2", "2^x"), each = 6))) %>%
  group_by(func)
df
#> # A tibble: 12 × 3
#> # Groups:   func [2]
#>        x     y func 
#>    <dbl> <dbl> <fct>
#>  1     1     1 x^2  
#>  2     2     4 x^2  
#>  3     3     9 x^2  
#>  4     4    16 x^2  
#>  5     5    25 x^2  
#>  6     6    36 x^2  
#>  7     1     2 2^x  
#>  8     2     4 2^x  
#>  9     3     8 2^x  
#> 10     4    16 2^x  
#> 11     5    32 2^x  
#> 12     6    64 2^x

ggplot(df, aes(x, y, color = func, linetype = func))  
  geom_point()  
  geom_path()  
  scale_color_manual(values = c("red", "black"))

Created on 2023-01-31 by the reprex package (v2.0.1)

  • Related