每个面有不同的 y 轴断裂

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

我正在尝试在循环中创建不同的条形图,显示每个物种和区域的计数,按区域划分。我的 df 的结构是这样的:

# Sample data frame structure 
  max_counts <- data.frame(
    Region = c("Eco1", "Eco1", "Eco2", "Eco2"),
    Date = c(1, 2, 1, 2),
    max_count = c(10, 15, 8, 12),
    rounded_max_count = c(10, 15, 10, 15)
  )
  
  # Replicate the data frame for multiple species
  species_list <- c("Sp1", "Sp2", "Sp3")
  max_counts_list <- list()
  for (species in species_list) {
    max_counts_species <- max_counts
    max_counts_species$Species <- species
    max_counts_list[[length(max_counts_list) + 1]] <- max_counts_species
  }
  
  # Combine the replicated data frames into one
  max_counts_df <- do.call(rbind, max_counts_list)

我希望每个方面的 y 轴都是自己的,而不是共享的公共 y 轴,因为在某些地区有很多记录,而在其他地区只有很少的记录。由于多次尝试让我的条形达到了构面的顶部,并且我想要一些填充,所以我创建了一个列,将最大值四舍五入到最接近的 5 的倍数。我现在需要每个区域上的 y max 标签作为四舍五入的 ymax 值那个特定的区域。我尝试了很多方法,但关闭方法如下所示:

 # Create the plot
      plot <- ggplot(max_counts, aes(x = Date, y = max_count, fill = Region)) +
        geom_bar(stat = "identity") +
        scale_fill_manual(values = mycolors) +  
        facet_wrap(~ Region, ncol = 1, scales = "free_y") +  
        scale_x_continuous(breaks = seq(min(filtered_ecoregions$Date), max(filtered_ecoregions$Date), by = 1)) +
        scale_y_continuous(breaks = seq(0, max(max_counts$rounded_max_count), by = 5), expand = c(0, 0.01)) +
        theme_bw()

但它并没有完全做到这一点...我的尝试要么为所有面创建一个公共 y 轴,要么显示单独的面,但不显示 ymax 标签。

欢迎任何建议! 谢谢

r ggplot2 axis facet facet-wrap
1个回答
0
投票

问题是,只有位于刻度

breaks=
范围内的
limits=
才会显示。因此,对于
rounded_max_count
大于
max(max_count)
的所有面板,将不会显示您所需的“最大”值。

除此之外,如果您想为每个面板单独设置

limits=
,我建议您查看
ggh4x
包,它通过
ggh4x::facetted_pos_scales
允许为每个面板单独指定位置比例(包括
limits=
) .

library(ggplot2)
library(ggh4x)

# Create a list of y scales per panel
scale_y <- max_counts |>
  split(~Region) |>
  lapply(\(x) {
    scale_y_continuous(
      breaks = seq(0, max(x$rounded_max_count), by = 5), expand = c(0, 0.01),
      limits = c(0, max(x$rounded_max_count))
    )
  })

ggplot(max_counts, aes(x = Date, y = max_count, fill = Region)) +
  geom_bar(stat = "identity") +
  #scale_fill_manual(values = mycolors) +
  #scale_x_continuous(breaks = seq(min(filtered_ecoregions$Date), max(filtered_ecoregions$Date), by = 1)) +
  scale_x_continuous(breaks = scales::breaks_width(1)) +
  facet_wrap(~Region, ncol = 1, scales = "free_y") +
  ggh4x::facetted_pos_scales(
    y = scale_y
  ) +
  theme_bw()

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