简体   繁体   English

ggplot2 图例显示,但 plot 中的变量没有颜色

[英]ggplot2 legend showing but variables in plot don't have colour

I have been working on some code to plot a graph with multiple variables with a secondary Y axis and legend.我一直在研究 plot 的一些代码,该图具有多个变量以及辅助 Y 轴和图例。 I achieved this far with the examples below:我通过以下示例实现了这一点:

ggplot2 line chart gives "geom_path: Each group consist of only one observation. Do you need to adjust the group aesthetic?" ggplot2 折线图给出“geom_path:每个组仅包含一个观察值。您需要调整组审美吗?”

Adjusting the second y axis in ggplot2 调整 ggplot2 中的第二个 y 轴

Y limits for ggplot with sec.axis 带有 sec.axis 的 ggplot 的 Y 限制

However, I am currently sitting with two versions of the same graph.但是,我目前正在使用同一图表的两个版本。 One has no colour in the plot itself but includes a legend with the correct colours for each variable and a second graph that has colour in the plot but no legend shows.一个在 plot 本身中没有颜色,但包括一个为每个变量提供正确颜色的图例,以及在 plot 中具有颜色但没有显示图例的第二个图。 Please the the plots and code below.请看下面的图和代码。

I am aware it is something to do with the geom_point() code line as I saw in the answer from this previous question: Reasons that ggplot2 legend does not appear我知道这与geom_point()代码行有关,正如我在上一个问题的答案中看到的那样: ggplot2 图例未出现的原因

colour= XYZ should be inside the aes(),not outside colour= XYZ 应该在 aes() 内部,而不是外部

geom_point(aes(data, colour=XYZ)) #------>legend geom_point(aes(data, colour=XYZ)) #------>图例

geom_point(aes(data),colour=XYZ) #------>no legend geom_point(aes(data),colour=XYZ) #------>没有图例

Please find a chunk of the dataset below:请在下面找到一部分数据集:

h1enraw <-structure(list(run = c(1738, 1739, 1740, 1741, 1742, 1743),
                          temp = c(19, 19, 19, 19, 21, 22),
                          avgbase = c(1386, 1386, 1389, 1389, 1352, 1336),
                          no2c = c(6.98, 6.96, 6.94, 6.99, 7.01, 7.01),
                          no3c = c(18.52, 17.6, 18.77, 19.81, 18.22, 18.60)), 
                     row.names = c(NA, 6L), class = "data.frame")

In line with the quoted code above I understand why one of my graph versions has a legend and the other one does not.根据上面引用的代码,我理解为什么我的一个图形版本有图例而另一个没有。 I just do not understand how this impacts the variables within the graph to have colour or not.我只是不明白这如何影响图表中的变量是否有颜色。 I would really appreciate it if someone could point me to the right direction.如果有人能指出我正确的方向,我将不胜感激。

Graph with no colour but showing the legend没有颜色但显示图例的图表

# Choose number for dividing second Y axis
scaleRight <- 40
ymax <-43

h1no2<-ggplot(h1enraw, aes(x=run)) +
  geom_path(aes(y=temp, group=1,colour="cornflowerblue"), size=0.9) +
  geom_point(aes(y=no2c, group=1,colour="red")) +
  geom_point(aes(y=no3c, group=1,colour="darkgreen")) +
  geom_line(aes(y=avgbase/scaleRight, group=1,colour="chocolate1"), size=0.9) +
  scale_y_continuous(breaks=seq(0,40,2), expand = expansion(mult = c(0,.05)),
                     sec.axis = sec_axis(~.*scaleRight, name = "Average Baseline (Transmitance Units)")) +
  coord_cartesian(ylim = c(0, ymax)) +
  theme_classic() +
  labs( y="Temperature (°C) / Concentration (ppm)", x="Run", title = "H1 - High Temperature Cycle") +
  theme(text = element_text(size=9),
        axis.text.x = element_text(angle=90, vjust=0.6),
        axis.text=element_text(size=12),
        axis.title=element_text(size=14,face="bold"),
        panel.border = element_rect(colour = "chocolate1", fill=NA, size=0.5),
        legend.position = "bottom", legend.title=element_text(size=10), legend.text = element_text(size=8),
        axis.title.y = element_text(size=10),
        plot.title = element_text(size=14, face="bold")) +
  theme(legend.title=element_blank()) + 
  scale_fill_manual(breaks=c("temp","no2c","no3c","avgbase"),
                    labels=c("Temperature", "NO2", "NO3", "Avg Baseline"),
                    values = c("temp"="cornflowerblue", "no2c"="red",
                               "no3c"="darkgreen", "avgbase"="chocolate1")) + 
  scale_color_manual(labels = c("Temperature", expression(NO[2]), expression(NO[3]), "Avg Baseline"),
                     values = c("temp"="cornflowerblue", "no2c"="red",
                                "no3c"="darkgreen", "avgbase"="chocolate1"),
                     breaks=c("temp","no2c","no3c","avgbase"))

Plot with legend but variables in plot do not have colour Plot 有图例,但 plot 中的变量没有颜色

Graph with colour but no legend有颜色但没有图例的图表

# Choose number for dividing second Y axis
scaleRight <- 40
ymax <-43

h2no2<-ggplot(h2enraw, aes(x=run)) +
  geom_path(aes(y=temp, group=1), colour="cornflowerblue", size=0.9) +
  geom_point(aes(y=no2c, group=1 ),colour="red") +
  geom_point(aes(y=no3c, group=1 ),colour="darkgreen") +
  geom_line(aes(y=avgbase/scaleRight, group=1 ),colour="chocolate1", size=0.9) +
  scale_y_continuous(breaks=seq(0,40,2), expand = expansion(mult = c(0,.05)),
                     sec.axis = sec_axis(~.*scaleRight, name = "Average Baseline (Transmitance Units)")) +
  coord_cartesian(ylim = c(0, ymax)) +
  theme_classic() +
  labs( y="Temperature (°C) / Concentration (ppm)", x="Run", title = "H2 - High Temperature Cycle") +
  theme(text = element_text(size=9),
        axis.text.x = element_text(angle=90, vjust=0.6),
        axis.text=element_text(size=12),
        axis.title=element_text(size=14,face="bold"),
        panel.border = element_rect(colour = "chocolate1", fill=NA, size=0.5),
        legend.position = "bottom", legend.title=element_text(size=10), legend.text = element_text(size=8),
        axis.title.y = element_text(size=10),
        plot.title = element_text(size=14, face="bold")) +
  scale_fill_manual(name="Legend",
                    breaks=c("temp","no2c","no3c","avgbase"),
                    labels=c("Temperature", "NO2", "NO3", "Avg Baseline"))

Plot with colour and no legend Plot 有颜色无图例

Thank you so much太感谢了

Option 1选项1

This should work for you.这应该适合你。

I calculated a scaled version of avgbase , then I transformed your data into long-format.我计算了avgbase的缩放版本,然后将您的数据转换为长格式。 Because this generally helps when you want to group variables within a plot.因为当您想要在 plot 中对变量进行分组时,这通常会有所帮助。

In ggplot() , I filter in every geom_ the specific data points I want to plot (ie, in geom_line() I filter for temp and avgbase_scaled because I want them plotted as lines).ggplot()中,我在每个geom_中过滤我想要 plot 的特定数据点(即在geom_line()中,我过滤tempavgbase_scaled因为我希望它们绘制为线)。

library(tidyverse)

h1enraw <-structure(list(run = c(1738, 1739, 1740, 1741, 1742, 1743),
                         temp = c(19, 19, 19, 19, 21, 22),
                         avgbase = c(1386, 1386, 1389, 1389, 1352, 1336),
                         no2c = c(6.98, 6.96, 6.94, 6.99, 7.01, 7.01),
                         no3c = c(18.52, 17.6, 18.77, 19.81, 18.22, 18.60)), 
                    row.names = c(NA, 6L), class = "data.frame")

scaleRight <- 40
ymax <- 43

h1enraw %>%
  mutate(avgbase_scaled = avgbase/scaleRight, .keep = "unused") %>%
  pivot_longer(c(-run), names_to = "value_type", values_to = "value") %>%
  ggplot(aes(x = run, color = value_type)) +
  geom_line(data = . %>% filter(value_type %in% c("avgbase_scaled",
                                                  "temp")),
            aes(y = value), size=0.9)+
  geom_point(data = . %>% filter(value_type %in% c("no2c",
                                                  "no3c")),
            aes(y = value), size=1)+
  scale_y_continuous(breaks=seq(0,40,2), expand = expansion(mult = c(0,.05)),
                     sec.axis = sec_axis(~.*scaleRight, name = "Average Baseline (Transmitance Units)"))+
  coord_cartesian(ylim = c(0, ymax)) +
  theme_classic() +
  labs( y="Temperature (°C) / Concentration (ppm)", x="Run", 
        title = "H1 - High Temperature Cycle") +
  theme(text = element_text(size=9),
        axis.text.x = element_text(angle=90, vjust=0.6),
        axis.text=element_text(size=12),
        axis.title=element_text(size=14,face="bold"),
        panel.border = element_rect(colour = "chocolate1", fill=NA, size=0.5),
        legend.position = "bottom", 
        legend.title=element_blank(), 
        legend.text = element_text(size=8),
        axis.title.y = element_text(size=10),
        plot.title = element_text(size=14, face="bold"))+
  scale_color_manual(labels = c("Temperature", expression(NO[2]), expression(NO[3]), "Avg Baseline"),
                     values = c("temp"="cornflowerblue", "no2c"="red",
                                "no3c"="darkgreen", "avgbase_scaled"="chocolate1"),
                     breaks=c("temp","no2c","no3c","avgbase_scaled"))

Created on 2022-08-30 with reprex v2.0.2使用reprex v2.0.2创建于 2022-08-30

Option 2选项 2

Here an option without data transformation: You have to use the color parameter within aes() and assign the correct colnames:这是一个没有数据转换的选项:您必须在aes()中使用color参数并分配正确的列名:

scaleRight <- 40
ymax <-43

ggplot(h1enraw, aes(x=run)) +
  geom_path(aes(y=temp, color="temp"), size=0.9) +
  geom_point(aes(y=no2c, color="no2c")) +
  geom_point(aes(y=no3c, color="no3c"))+
  geom_line(aes(y=avgbase/scaleRight, color="avgbase"), size=0.9) +
  scale_y_continuous(breaks=seq(0,40,2), expand = expansion(mult = c(0,.05)),
                     sec.axis = sec_axis(~.*scaleRight, name = "Average Baseline (Transmitance Units)")) +
  coord_cartesian(ylim = c(0, ymax)) +
  theme_classic() +
  labs( y="Temperature (°C) / Concentration (ppm)", x="Run", 
        title = "H1 - High Temperature Cycle") +
  theme(text = element_text(size=9),
        axis.text.x = element_text(angle=90, vjust=0.6),
        axis.text = element_text(size=12),
        axis.title = element_text(size=14,face="bold"),
        legend.position = "bottom", 
        legend.title = element_blank(), 
        legend.text = element_text(size=8),
        axis.title.y = element_text(size=10),
        plot.title = element_text(size=14, face="bold"))+
  scale_color_manual(labels=c("Temperature", "NO2", "NO3", "Avg Baseline"),
                     values = c("temp"="cornflowerblue", "no2c"="red",
                                "no3c"="darkgreen", "avgbase"="chocolate1"))

Created on 2022-08-30 with reprex v2.0.2使用reprex v2.0.2创建于 2022-08-30

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM