R 图图例中的项目顺序根据相同数据的不同数据集而不同

问题描述 投票:0回答:1

对于 R 和 Stack Overflow 来说是新事物,但我编写了一些 R 代码来按季节和地点制作叶绿素数据的分组箱线图,同时包含水质标准参考线。它可能不是最优雅或最正确的脚本,但它似乎可以完成工作。但是,它会根据我使用的数据集以不同的方式对图例中的项目进行排序。请参阅下面的示例图。在一种情况下,WQ 标准列在站点列表下方,而在另一种情况下,则将其放置在站点列表上方。我希望能够控制图例中不同项目的顺序/位置。

# Load libraries
library(readxl)
library(ggplot2)
library(dplyr)
library(tidyverse)
library(lubridate)
library(cowplot)
library(patchwork)
library(ggtext)
library(NADA)

Site <- c("Site 1","Site 8","Site 10","Site 3")
Season <- c("Win", "Spr", "Sum", "Fall")
Chla <- c(5, 10, 15, 20)

Sample_data <- data.frame(Site, Season, Chla)
newsam <- Sample_data
newsam$Site <- factor(newsam$Site, levels = c("Site 1", "Site 3", "Site 8", "Site 10"))
newsam %>% arrange(desc(Site))

#WQ line under site list
ggplot(Sample_data, aes(x=factor(Season), y=Chla, fill=factor(Site))) + 
  geom_hline(aes(yintercept = 10, linetype = "WQ Criteria"), color = "gray", 
             size =1) +
  geom_hline(aes(yintercept = 0.5, linetype = "Reporting Limit"), color = "red", size = 1) +
  geom_boxplot() +
  stat_summary(fun.y=mean, geom="point", shape=4, size=3, color="black",  
               position = position_dodge2(width = 0.75, preserve = "single")) +
  labs(x = "Season", y = "Chlorophyll α (mg/m<sup>3</sup>)", linetype="", fill="") +
  theme_classic() +
  theme(
    axis.title.x = element_markdown(),
    axis.title.y = element_markdown() 
  ) +
  scale_x_discrete(limits = c("Win", "Spr", "Sum", "Fall")) +
  scale_fill_brewer(palette = "Paired") +
  ggtitle("Keystone Lake Chlorophyll, 2013-2022") +
  theme(plot.title = element_text(hjust = 0.5))

#WQ line over site list
ggplot(newsam, aes(x=factor(Season), y=Chla, fill=factor(Site))) + 
  geom_hline(aes(yintercept = 10, linetype = "WQ Criteria"), color = "gray", 
             size =1) +
  geom_hline(aes(yintercept = 0.5, linetype = "Reporting Limit"), color = "red", size = 1) +
  geom_boxplot() +
  stat_summary(fun.y=mean, geom="point", shape=4, size=3, color="black",  
               position = position_dodge2(width = 0.75, preserve = "single")) +
  labs(x = "Season", y = "Chlorophyll α (mg/m<sup>3</sup>)", linetype="", fill="") +
  theme_classic() +
  theme(
    axis.title.x = element_markdown(),
    axis.title.y = element_markdown() 
  ) +
  scale_x_discrete(limits = c("Win", "Spr", "Sum", "Fall")) +
  scale_fill_brewer(palette = "Paired") +
  ggtitle("Keystone Lake Chlorophyll, 2013-2022") +
  theme(plot.title = element_text(hjust = 0.5))

[带有“sample_data”的图表(https://i.sstatic.net/GPqIoRmQ.png)]

[带有“newsam”的图表(https://i.sstatic.net/gwsf6hWI.png)]

我尝试使用guide_legend和override.aes。

ggplot2 legend boxplot geom-hline
1个回答
0
投票

您已经通过将

newsam
设置为因子并设置级别,使用
Site
完成了图表的操作:

newsam$Site <- factor(newsam$Site, levels = c("Site 1", "Site 3", "Site 8", "Site 10"))

只需在调用

Sample_data
之前或通过指定在
ggplot
的美观内将
levels
参数添加到
fill=factor(Site)
来使用
ggplot
对绘图执行相同的操作即可。

© www.soinside.com 2019 - 2024. All rights reserved.