簡體   English   中英

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中對因子變量進行排序[ 鏈接 ]
  • 按兩列訂購數據框[ 鏈接 ]

下面的方法使用了這兩個鏈接。 首先根據組別對數據進行重新排序,然后按Label降序排列(因為您希望Label以相反的順序顯示(即coord_flip()之后的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()

以相反的順序重新排列因子

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM