首页 > 解决方案 > 根据ggplot2中最后一个分面网格的递减值对条形图的Y轴进行排序

问题描述

问题
我正在尝试根据具有公共 Y 轴标签的最后一个方面组“Step4”的递减值对条形图的 Y 轴进行排序。有一些建议可以对它们内部的所有构面组进行排序,但是如何处理一个构面组的公共 y 轴标签和值。我附上了初始图的示例数据和代码以理解问题。提前致谢。

数据
在此处下载示例数据

代码

library(ggplot2)
library(reshape2)

#reading data
data <- read.csv(file = "./sample_data.csv", stringsAsFactors = TRUE)

#reshaping data in longer format using reshape::melt
data.melt <- melt(data)

#plotting the data in multi-panel barplot
ggplot(data.melt, aes(x= value, y=reorder(variable, value))) +
  geom_col(aes(fill = Days), width = 0.7) +
  facet_grid(.~step, scales = "free")+
  theme_pubr() + 
  labs(x = "Number of Days", y = "X")

图表样本数据的条形图

标签: rggplot2data-visualizationfacet

解决方案


汇总 last 的值'step'并从数据中提取级别。

library(dplyr)
library(ggplot2)

lvls <- data.melt %>%
  arrange(step) %>%
  filter(step == last(step)) %>%
  #Or
  #filter(step == 'Step4') %>%
  group_by(variable) %>%
  summarise(sum = sum(value)) %>%
  arrange(sum) %>%
  pull(variable)

data.melt$variable <- factor(data.melt$variable, lvls)

ggplot(data.melt, aes(x= value, y= variable)) +
  geom_col(aes(fill = days), width = 0.7) +
  facet_grid(.~step, scales = "free")+
  theme_pubr() + 
  labs(x = "Number of Days", y = "X")

在此处输入图像描述


推荐阅读