R语言 如何在geom_col中使列与负y数据和正y数据堆叠

cgvd09ve  于 2023-05-20  发布在  其他
关注(0)|答案(1)|浏览(186)

我试图在ggplot中创建一个将列堆叠在一起的图形,而不是重叠它们,其中包括每个y轴变量的负值和正值。以下是我的数据集的示例:

Depth<-c("75", "200", "350", "850", "1000")
BDay<-c(0, 0, 0, 0, 0)
BNight<-c(0, -1, -1, 0, 0)
CDay<-c(0, 0, 5, 23, 6)
CNight<-c(0, 0, -5, -36, -8)
df<-data.frame(Depth, BDay, BNight, CDay, CNight)
df

下面是我的图代码示例:

ggplot(df, aes(x=as.factor(Depth))) + 
  geom_col(aes(y = BDay,      fill="Species B"),    position=position_stack(reverse = TRUE)) +
  geom_col(aes(y = BNight,    fill="Species B"),    position=position_stack(reverse = TRUE)) +
  geom_col(aes(y = CDay,      fill="Species C"),    position=position_stack(reverse = TRUE)) + 
  geom_col(aes(y = CNight,    fill="Species C"),    position=position_stack(reverse = TRUE)) + 
  xlim("1000", "850", "350", "200", "75") +
  scale_y_continuous(breaks = seq(-40,40,5),limits = c(-40,40))+
  labs(title = "CTA Spring", x="Transect Depth (m)", y="Observations", fill="Species") +
  coord_flip() +
  geom_hline(yintercept = 0, linetype="dashed") +
  theme_classic()+
  theme(axis.text.y = element_text(size = 15))+
  theme(axis.text.x = element_text(size = 12))

下面是输出。如您所见,值重叠而不是堆叠在350处,因此BNight的数据不可见。我添加了position=position_stack(reverse = TRUE),但这似乎没有解决问题。有别的解决办法吗?

bq9c1y66

bq9c1y661#

问题在于,您对每个系列使用单独的geom_col,因为您的数据位于单独的列中。相反,要获得堆叠条形图,您必须使用例如:tidyr::pivot_longer。这样,你就可以只用一个geom_col来制作图表,并且条形图会堆叠起来:

library(ggplot2)
library(tidyr)

df_tidy <- df %>%
  pivot_longer(-Depth,
    # Split column names into species and time of day
    names_to = c("species", "time"),
    names_pattern = c("(.)(.*)"),
    values_to = "value"
  )

ggplot(df_tidy, aes(y = as.factor(Depth))) +
  geom_col(aes(x = value, fill = interaction(species, time)),
    position = position_stack(reverse = TRUE)
  ) +
  ylim("1000", "850", "350", "200", "75") +
  scale_x_continuous(breaks = seq(-40, 40, 5), limits = c(-40, 40)) +
  labs(
    title = "CTA Spring", x = "Transect Depth (m)",
    y = "Observations", fill = "Species"
  ) +
  geom_vline(xintercept = 0, linetype = "dashed") +
  theme_classic() +
  theme(
    axis.text.y = element_text(size = 15),
    axis.text.x = element_text(size = 12)
  )

相关问题