【问题标题】:ggplot order bars within group组内的ggplot顺序条
【发布时间】:2018-04-15 16:05:23
【问题描述】:

我需要帮助来保持 x 轴变量组中条形的一致顺序。目前,在每个组中,条形图按 y 轴值的升序显示。

在上图中,X 变量取值 Low 或 High。 Group 变量也取值 Low 或 High。在这个条形图中,我需要蓝色条出现在 X=low 和 X=high 的红色条之前。提前致谢。

barplot1 <- structure(list(Y = c("1", "1.80", "2.80", "1.31"), 
lb = c("1", "0.84","1.55", "0.75"), ub = c("1", "3.88", "5.04", "2.28"),
X = structure(c(1L, 2L, 1L, 2L), .Label = c("Low", "High"), class = "factor"),
Group = structure(c(1L, 1L, 2L, 2L), .Label = c("Low", "High"), class = 
c("ordered", "factor"))), .Names = c("Y","lb", "ub", "X", "Group"), class = 
"data.frame", row.names = c("Low X, Low Group",                                                                         
"High X, Low Group", "Low X, High Group", "High X, High Group"))

barplot1$X <- factor(barplot1$X,levels = c("Low","High"))
barplot1$Group <- factor(barplot1$Group,levels = c("Low","High"),ordered=T) 

example <-ggplot(barplot1, aes(x=X, y=Y, fill=Group)) +
  theme_minimal() +
  scale_fill_manual(values=c("#0073C2B2","#DC0000B2")) +
  geom_bar(stat="identity", position = position_dodge()) +
  geom_errorbar(aes(ymin = lb, ymax = ub), width=.2, position=position_dodge(.9)) +
  ggtitle("Example") +
  labs(x="X",y="Y") +
  labs(fill = "Group",size=12) +
  theme(plot.title = element_text(size=14,face="bold",hjust = 0.5),
 axis.text=element_text(size=12),axis.title=element_text(size=14,face="bold"),
    legend.text = element_text(size=12),legend.title = element_text(size=14),
    plot.caption = element_text(size = 12))

【问题讨论】:

  • 请确保提供带有问题的示例数据集,以便我们能够重现错误。 This question 提供了一些关于如何操作的提示,但通常最好使用 data.frame() 函数生成一个小数据帧,或者使用 dput() 复制数据
  • 谢谢,米奇。我已编辑帖子以包含示例数据集。

标签: r ggplot2


【解决方案1】:

我们可以使用dplyrforcats 重新排列蓝色条。由于您的数据结构,我们必须将任何字符变量转换为数字类型。否则,我们将无法重新排序因子:

library(ggplot2)
library(forcats)
library(dplyr) 

barplot1 %>% 
  mutate_if(is.character, as.numeric) %>% 
  ggplot(aes(fct_reorder(X, Y, .desc = TRUE), Y, fill = Group)) +
  geom_col(position = "dodge") +
  geom_errorbar(aes(ymin = lb, ymax = ub), width = 0.2, position = position_dodge(.9)) +
  scale_fill_manual(values = c("#0073C2B2", "#DC0000B2")) +
  labs(title = "Example",
       x = "X") +
  theme_minimal() +
  theme(
    plot.title = element_text(size = 14, face = "bold", hjust = 0.5),
    axis.text = element_text(size = 12), 
    axis.title = element_text(size = 14, face = "bold"),
    legend.text = element_text(size = 12), 
    legend.title = element_text(size = 14),
    plot.caption = element_text(size = 12)
  )

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-03-08
    • 1970-01-01
    • 2014-09-29
    • 1970-01-01
    • 2020-10-16
    • 2021-02-02
    • 2017-07-21
    相关资源
    最近更新 更多