在单独的堆积条形图中将分类列条目绘制为总和

Plotting categorical column entries as sums in separate stacked bar plot

我想从本质上重新创建我在 JMP 中但使用 R 绘制的图。这些值来自定性数据集,其中物种组是单个列中的条目。我想在 x 轴上绘制 SpeciesGroup,但在堆叠条中按强度填充颜色。我想我需要重新排序数据,但不太清楚如何。

df<- data.frame(ID=c(1,2),
                policy=c("Policy A", "Policy B", "Policy C", "Policy D", 
                         "Policy E","Policy F" ),
                SpeciesGroup= c("ray", "ray", "mammal", "mammal", "fish", "reptile"),
                Stength=c("M", "V", "M", "P", "P", "M"),
                stringsAsFactors=FALSE)

到目前为止我已经尝试过:

ggplot(aes(x=factor(Group), fill = Regulatory_Strength)) +
  geom_bar(mapping = NULL, data = RFMO_Policies, stat = "count",
           position = "stack",  width = .7, binwidth = NULL,
           na.rm = FALSE, show.legend = TRUE, inherit.aes = TRUE )+
  labs(title="Policy Directives by Taxa",  x="Directive Type", y = "Count", size = 13 )+
  theme(plot.title = element_text(hjust=1))+
  theme_classic()+
  scale_fill_manual(values=c( "firebrick3","yellow1","dodgerblue1" ), 
                    labels= c("Mandatory","Partial", "Voluntary" ))+
  theme(axis.text.x=element_text(angle=45,hjust=1,vjust=1, size= 13))+
  guides(fill=guide_legend(title="Regulatory Strength"))

下面是我在 JMP 中制作的图表,我想重现:

感谢您提供的任何帮助!!

是您要找的吗?

library(ggplot2)
ggplot(df, aes(x = SpeciesGroup, fill =  Stength))+
  geom_bar(stat = "count")

替代使用geom_tile

在我看来,由于您的数据是定性值,使用 geom_tile:

绘制它们可能更有意义
library(dplyr)
All_val <- expand(df,SpeciesGroup, Stength)

library(ggplot2)
df %>% mutate(Val = Stength) %>%
    select(SpeciesGroup, Stength, Val) %>%
    full_join(., All_val) %>%
    ggplot(aes(x = SpeciesGroup, y = Stength, fill = Val))+
    geom_tile(color = "black")+
    scale_fill_discrete(na.value = "white")+
    geom_text(aes(label = Val))