组内的ggplot订单栏

时间:2018-04-15 16:05:24

标签: r ggplot2

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

Here's an image of the current issue

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

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))

1 个答案:

答案 0 :(得分:0)

我们可以使用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)
  )

enter image description here