简体   繁体   English

使用 ggplot2 为堆叠条形图维护 dataframe 的订单

[英]Mantain order of dataframe for a stacked barplot using ggplot2

Using the following dataframe and ggplot...使用以下 dataframe 和 ggplot...

sample ="BC04"
df<- data.frame(Name=c("Pseudomonas veronii", "Pseudomonas stutzeri", "Janthinobacterium lividum", "Pseudomonas viridiflava"),
                 Abundance=c(7.17, 4.72, 3.44, 3.33))

ggplot(data=df, aes(x=sample, y=Abundance, fill=Name)) +
  geom_bar(stat="identity")

... creates the following graph ...创建以下图表

barplot条形图

Altough the "geom_bar(stat="identity")" is set to "identity", it still ignores the order in the dataframe.尽管 "geom_bar(stat="identity")" 设置为 "identity",但它仍然忽略 dataframe 中的顺序。 I would like to get a stack order based on the Abundance percentage ( Highest percentage at the top with ascending order )我想根据丰度百分比获得堆叠顺序(最高百分比在顶部,升序排列

Earlier, strings passed to ggplot , are evaluated with aes_string (which is now deprecated).早些时候,传递给ggplot的字符串是用aes_string评估的(现在已弃用)。 Now, we convert the string to sym bol and evaluate ( !! )现在,我们将字符串转换为sym并计算 ( !! )

library(ggplot2)
ggplot(data=df, aes(x= !! rlang::sym(sample), y=Abundance, fill=Name)) +
  geom_bar(stat="identity")

Or another option is .data或者另一种选择是.data

ggplot(data=df, aes(x= .data[[sample]]), y=Abundance, fill=Name)) +
  geom_bar(stat="identity")

Update更新

By checking the plot, it may be that the OP created a column named 'sample.通过检查 plot,可能是 OP 创建了一个名为 'sample. In that case, we reorder the 'Name' based on the desc ending order of 'Abundance'在这种情况下,我们根据“Abundance”的desc对“名称” reorder

df$sample <- "BC04"
ggplot(data = df, aes(x = sample,  y = Abundance, 
  fill = reorder(Name, desc(Abundance)))) + 
       geom_bar(stat = 'identity')+ 
       guides(fill = guide_legend(title = "Name"))

-output -输出

在此处输入图像描述


Or another option is to convert the 'Name' to factor with levels mentioned as the unique elements of 'Name' (as the data is already arranged in descending order of 'Abundance')或者另一种选择是将“名称”转换为“名称”的unique元素提到的levelsfactor (因为数据已经按“丰度”的降序排列)

library(dplyr)
df %>%
  mutate(Name = factor(Name, levels = unique(Name))) %>% 
  ggplot(aes(x = sample, y = Abundance, fill = Name)) +
     geom_bar(stat = 'identity')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM