如何在ggplot2中为不同面添加水平线

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

我想在 ggplot2 中的 facet_wrap 图中向条形图添加水平线。我有两种营养素类型,每种营养素类型都有我想要显示的不同指导值,并且我希望这些图在单个框架中并排显示。数据如下:

Trip   Depth       NutrientType   ugL
  <fct>  <fct>       <chr>        <int>
1 Before Surface     TN            1111
2 Before Surface     TP             162
3 Before Near bottom TN            1428
4 Before Near bottom TP             191
5 After  Surface     TN             869
6 After  Surface     TP             756
7 After  Near bottom TN             816
8 After  Near bottom TP             487

当前代码:

BARR1plot <- ggplot(BARR1,
                    aes(x=Depth,
                        y=ugL,
                        fill=Trip))+
  geom_bar(colour="black",stat="identity",position="dodge")+
  scale_fill_manual(values=colours)+
  theme_classic()+
  theme(text=element_text(size=18))+
  theme(axis.text.x=element_text(angle=90,hjust=1,vjust=0.5,size=12))+
  theme(axis.title.y=element_text(size=16))+
  theme(legend.title=element_blank())+
  ylab("Concentration (µg/L)")+
  xlab("")+
  facet_grid(~NutrientType,scales="fixed", switch="x")+
  labs(title="BARR1")+
  theme(plot.title=element_text(hjust=0))+
  theme(panel.spacing=unit(0,"mm"))
BARR1plot

我已经搜索了之前的问题,并使用 geom_hline 将代码添加到了现有的绘图代码中,但是两条线都出现在两个绘图中,而不仅仅是与其相关的营养类型。目前使用此代码:

data_hline <- data.frame(group=unique(BARR1$NutrientType),hline=c(900,250))

BARR1plot+geom_hline(data=data_hline,aes(yintercept=hline))

但是得到这个结果: Plot

谢谢!

ggplot2 facet-wrap geom-hline
1个回答
0
投票

问题是您通过

NutrientType
进行分面,但在
geom_hline
的数据中,您将包含营养素类型的列命名为
group
。因此,该数据不会被分面,并且两条线都将显示在两个分面面板中。

要修复该问题,请重命名您的列。

library(ggplot2)

data_hline <- data.frame(
  NutrientType = unique(BARR1$NutrientType),
  hline = c(900, 250)
)

BARR1plot +
  geom_hline(
    data = data_hline,
    aes(yintercept = hline)
  )

数据

BARR1 <- structure(list(Trip = c(
  "Before", "Before", "Before", "Before",
  "After", "After", "After", "After"
), Depth = c(
  "Surface", "Surface",
  "Near bottom", "Near bottom", "Surface", "Surface", "Near bottom",
  "Near bottom"
), NutrientType = c(
  "TN", "TP", "TN", "TP", "TN",
  "TP", "TN", "TP"
), ugL = c(
  1111L, 162L, 1428L, 191L, 869L, 756L,
  816L, 487L
)), class = "data.frame", row.names = c(
  "1", "2", "3",
  "4", "5", "6", "7", "8"
))
© www.soinside.com 2019 - 2024. All rights reserved.