I am reopening the discussion I had here: Problem displaying correct data in legend
I would like to know if there is an easy way to display legend color references when 2 parameters have the same color curves or points. Here is the script showing that the plot's legend displays only one of the 2 parameters in red:
library("tidyverse")
library("lubridate")
library("ggplot2")
Time <- c("09-01-2023 12:07:09","09-01-2023 12:17:09","09-01-2023 12:27:09","09-01-2023 12:37:09")
Width <- c(3,4,5,6)
Length <- c(30,40,50,60)
Weight <- c(300,400,500,600)
Angle <- c(3000,4000,5000,6000)
DF <- data.frame(Time,Width,Length,Weight,Angle)
DF<- DF %>% mutate(Time=dmy_hms(Time))
DF_Tidy<-gather(DF,key=Parameters,value=Values,-Time)
Colors<-c("red","red","red","red","blue","blue","blue","blue",
"red","red","red","red","green","green","green","green")
Units <-c("mm","mm","mm","mm","mm","mm","mm","mm","kg","kg","kg","kg","Deg","Deg","Deg","Deg")
DF_Tidy<-data.frame(DF_Tidy,Units,Colors)
Graph_DF<-DF_Tidy %>%
ggplot(aes(x=Time, y=Values,color=Colors))
geom_point()
scale_color_identity(
guide = "legend",
labels = setNames(DF_Tidy$Parameters, DF_Tidy$Colors))
theme(axis.text.x = element_text(size = 10),axis.text.y = element_text(size = 10),
legend.text=element_text(size=8),legend.key.size = unit(0.5,"line"),legend.position = "bottom")
facet_wrap(facets = (~ Units),scales="free_y",nrow=4)
plot(Graph_DF) `
I have attached the plot legend result. If I replace one the 2 sets of 4 red colors by a set of 4 brown colors, I do get 4 colors (red, blue, brown, green) in my legend (because there are no 2 parameters with the same color (red))
In other words, I would like the legend to appear as below:
blue point: Length red point: Width red point: Weight green point: Deg
Is there a way to do this (another way than the one provided in my last post)? Thank you for your help. User
CodePudding user response:
Add:
guides(color = guide_legend(label.position = "left"))
to the call to ggplot.
Created on 2023-01-13 with reprex v2.0.2
CodePudding user response:
Maybe you want to use interaction
to combine the color
and shape
to have 2 labels with red colors like this:
library(tidyverse)
library("lubridate")
library("ggplot2")
Graph_DF<-DF_Tidy %>%
ggplot(aes(x=Time, y=Values,color=interaction(Colors, Parameters), shape = interaction(Colors, Parameters)))
geom_point()
scale_colour_manual(name = "legend",
values = c("blue", "green", "red", "red"),
labels = c("Length", "Deg", "Width", "Weight"))
scale_shape_manual(name = 'legend',
values = c(16, 16, 16, 17),
labels = c("Length", "Deg", "Width", "Weight"))
theme(axis.text.x = element_text(size = 10),axis.text.y = element_text(size = 10),
legend.text=element_text(size=8),legend.key.size = unit(0.5,"line"),legend.position = "bottom")
facet_wrap(facets = (~ Units),scales="free_y",nrow=4)
plot(Graph_DF)
Created on 2023-01-13 with reprex v2.0.2