在 ggplot 中堆叠和分组条形图,同时保持 y 比例

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

我正在开展一个项目,使用 R 分析浮游植物数据,并尝试评估色素比例在一年中的变化模式。

下面给出了我的一个图的代码。它运行良好(请参阅![有效 jpg] plot by sample ID),即将颜料绘制为 100% 的比率,这正是我想要的,因为我们正在查看相对颜料比率。

但是,没有明确的时间变量(我希望月份是明显的)。如果我将

x aes
更改为
month
,堆叠图的总和会变为不同的值,因为每个月的数据点数量不同(请参阅 plot by month)。

我尝试过使用

facet_wrap(~month)
,但这使得数据在我看来不清楚。理想情况下,我会让条形总和仍然为 100%,如
seq
所示,但也通过
month
进行一些清晰的分隔,以便我可以制作类似照片的内容 pigments with depth(我使用不同的方法制作的),但按月分开。

我希望这是清楚的 - 这是一个相当复杂的问题,这是我第一次提出问题,所以我希望它不是太胡扯!

plot_data <- shallowest_sample %>%select(all_of(selected_columns)) %>%pivot_longer(cols = -c(Id, lat, lon, depth, Unique_ID,decy,seq,month), names_to = "Pigment", values_to = "Percentage") %>%mutate(Pigment = sub("^normalised_", "", Pigment)) %>%group_by(month)

pigment_ratios_shallow <- ggplot(plot_data, aes(fill = factor(Pigment), y = Percentage, x = seq)) 
    + geom_bar(position = 'stack', stat = 'identity') 
    + labs(title = "Normalized Accessory Pigment Distribution for surface waters",x = "Sample ID",y = "Percentage") 
    + scale_y_continuous(labels = scales::percent_format(scale = 100))
    + theme_minimal()
pigment_ratios_shallow
r ggplot2 geom-bar stacked-bar-chart
1个回答
0
投票

新答案: 您可以通过每月的样本数量进行标准化。

df = tibble(  id = rep(1:30), # 30 ID
              month = c( rep(1, 15), rep(2, 10),rep(3, 5)), # Unequal month numbers
              comp1= 0.1 ,  # Fist component: constant
              comp2 = rnorm(30, mean = 0.5, sd = 0.1)# Second component: random
              ) %>% 
  mutate(comp3 = 1- comp1 - comp2) # Third component: 1 - others


df %>% pivot_longer(comp1:comp3) %>% 
  group_by( month,name) %>% 
  mutate( n = n()) %>% 
  mutate(standardiez_value= value/n) %>% 
  ggplot(aes(x=month %>% as.factor(), fill =name, y= standardiez_value,
             group=name)) +
  geom_bar(stat="identity", col="black")

与我的旧答案(如下)相比,我们可以通过组件来改变可变性。然而,数据集的不平等增加了图表的阅读难度。

我仍然认为我没有以正确的方式表示数据,但很难理解你真正想要什么。

之前的回答:

如果我理解正确的话,你想要代表每个月每个组成部分的平均值。我的建议是计算每个月的月平均值。我制作了一个不平等的数据集:

library(tidyverse)
df = tibble(  id = rep(1:30), # 30 ID
              month = c( rep(1, 15), rep(2, 10),rep(3, 5)), # Unequal month numbers
              comp1= 0.1 ,  # Fist component: constant
              comp2 = rnorm(30, mean = 0.5, sd = 0.2)# Second component: random
              ) %>% 
  mutate(comp3 = 1- comp1 - comp2) # Third component: 1 - others

然后我

pivot_longer()
group_by()
summarise()
,在绘图之前。

df %>% pivot_longer(comp1:comp3) %>% 
  group_by( month,name) %>%  summarise(mean = mean(value)) %>% 
  ggplot(aes(x=month %>% as.factor(), fill =name, y= mean)) +
  geom_bar(stat="identity")

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