ggplot2:使用 geom_pointrange() 和 coord_flip() 按向量和单独组(例如 facet_wrap)指定的顺序显示间隔

ggplot2: Show intervals in order specified by a vector and separate groups (e.g. with facet_wrap) using geom_pointrange() and coord_flip()

我一直在尝试创建一个包含按特定顺序比较 "N1"、"NON-N1" 组的图。我的数据包含名为 "A"、"N1"、"NON-N1"、"Comb" 的不同组,我试图首先显示所有名为 "A" 的组,然后显示按特定顺序将 "N1"、"NON-N1" 分组,最后是名为 "Comb" 的组。我想在所有比较中显示 "N1" 与 "NON-N1"(之上),但我尝试的所有方法都失败了。 我也希望使用 facet_wrap 来分隔这些组,但似乎该函数不适用于 coord_flip()。但这甚至是次要的,因为我什至无法解决我的第一个问题。我可以重新排序数据框,但 ggplot 不服从。请帮助我了解如何解决这个问题。谢谢!

library(ggplot2)

df = structure(list(CI1 = c(-3.2, -2, -2.1, -4.4, -2.0, -2.0, -4.4, -2.0, -4.6, -4.6, -0.5, 2.3, 2.0, -2.0, 1.2, 0.01, 2.0), OR = c(-2.2, 2, -2.1, -2.4, 0.04, 0.004, -2.4, 0.26, -2.6, -2.6, 0.24, 2.4, 2.5, 0.02, 1.5, 0.15, 2.4), CI2 = c(4.34247, 5.05772, 4.96875, 5.26578, 1.91331, 1.87162, 3.78027, 4.55967, 4.07937, 4.50965, 3.54538, 3.97742, 3.5491, 2.41067, 2.73239, 2.3767, 3.55664), Label = structure(1:17, .Label = c("N1_A", "NON-N1_A", "N1_B", "NON-N1_B", "N1_C", "NON-N1_C", "N1_D", "NON-N1_H", "N1_H", "NON-N1_D", "N1_E", "NON-N1_E", "N1_F", "NON-N1_F", "N1_G", "NON-N1_G", "Comb"), class = "factor"), group = c("N1", "NON-N1", "N1", "NON-N1", "N1", "NON-N1", "N1", "NON-N1", "N1", "NON-N1", "N1", "NON-N1", "N1", "NON-N1", "A", "A", "Comb")), .Names = c("CI1", "OR", "CI2", "Label", "group"), class = "data.frame", row.names = c(12L, 4L, 8L, 11L, 10L, 13L, 9L, 5L, 6L, 7L, 3L, 2L, 1L, 14L, 17L, 16L, 18L))

# order wanted using the column "Label":
ordered.names = c("N1_G", "NON-N1_G", "N1_C", "NON-N1_C", "N1_F", "NON-N1_F", "N1_A", "NON-N1_A","N1_B", "NON-N1_B","N1_H", "NON-N1_H","N1_D", "NON-N1_D","N1_E", "NON-N1_E", "Comb")

df$group = factor(df$group, levels =c("A", "N1", "NON-N1", "Comb"))
# df <- transform(df, category2 = factor(Label))
df$Label = factor(df$Label, levels=ordered.names)
# df = df[order(df$Label),]
# df$Label <- factor(rev(df$Label), levels=rev(levels(df$Label)))

ggplot(df, aes(x=Label, y=OR, ymin=CI1, ymax=CI2, group=group, color=group)) + geom_pointrange() + coord_flip() 
# + facet_wrap(~group, scale="free_x")

假设您的问题是:如何从上到下按特定顺序(A、N1、NON-N1、Comb)绘制组。

首先,有用的链接:

  • Kohske 如何在 ggplot2 中排序因子变量 [link]
  • 按两列排列数据框 [link]

下面的方法同时使用了这两个链接。首先根据 group 然后 Label 重新排序您的数据(按降序排列,因为您希望 Label 反向显示顺序(即在 coord_flip() 之后从上到下)。其次,新因子 Label2 根据数据框中的出现进行排序。

df2 <- df[with(df, rev(order(Label, factor(group, Label)))),]  #Reverse reorder
df2$Label2 <- factor(df2$Label, as.character(df2$Label))       #Order of appearance

ggplot(df2, aes(x=Label2, y=OR, ymin=CI1, ymax=CI2, group=group, color=group)) + 
    geom_pointrange() + coord_flip()