Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change the color of legend elements in ggplot (R)

Tags:

r

ggplot2

Following is the sample code for the random chart:

library(ggplot2)
ggplot(mtcars,aes(x=mpg,y=wt,color=factor(vs)))+geom_line()+theme(legend.position="top",legend.direction = "horizontal",legend.title=element_blank(),legend.key = element_blank())

and following is the output from above code:

enter image description here

My requirement: Instead of having two lines denoted by 0 and 1 as legend elements, I only want legend texts "0" and "1" colored as "red" and "skyblue" (same as color of lines) and remove the lines. Is this possible?

like image 906
Metrics Avatar asked Sep 20 '25 10:09

Metrics


1 Answers

I've written a string legend guide in the ggh4x package, that you might find useful.

Example:

library(ggplot2)
library(ggh4x)

ggplot(mtcars,aes(x=mpg,y=wt,color=factor(vs))) +
  guides(colour = "stringlegend") +
  geom_line() +
  theme(legend.position="top",
        legend.direction = "horizontal",
        legend.title=element_blank(),
        legend.key = element_blank())

Created on 2021-03-19 by the reprex package (v0.3.0)

like image 60
teunbrand Avatar answered Sep 22 '25 17:09

teunbrand