R语言 如何正确显示图例中的颜色参考?

ve7v8dk2  于 2023-01-15  发布在  其他
关注(0)|答案(2)|浏览(178)

我现在重新开始我在这里进行的讨论:在图例中显示正确数据时出现问题
我想知道当两个参数具有相同的颜色曲线或点时,是否有一种简单的方法来显示图例颜色参考。下面的脚本显示图的图例仅以红色显示两个参数中的一个:

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)  `

我已经附上了绘图+图例结果。如果我用一组4种棕色颜色替换2组4种红色颜色中的一种,我的图例中会得到4种颜色(红色、蓝色、棕色、绿色)(因为没有2个参数具有相同的颜色(红色))
enter image description here
换句话说,我希望图例显示如下:
蓝色点:长度红色点:红点宽度:绿点重量:度
有没有办法做到这一点(除了我上一篇文章中提供的方法之外的另一种方法)?谢谢您的帮助。用户

jhiyze9q

jhiyze9q1#

增加:

guides(color = guide_legend(label.position = "left"))

对ggplot的调用。

创建于2023年1月13日,使用reprex v2.0.2

wlzqhblo

wlzqhblo2#

也许您想使用interaction来合并colorshape,以获得2个红色标签,如下所示:

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)

创建于2023年1月13日,使用reprex v2.0.2

相关问题