2017-04-20 23 views
2

我使用以下代碼由數據幀:重新排序巴圖 - R,ggplot,位置= 「躲避」

> p <- rep(c("5e-8", "0.05", "1"), 2) 
> pgc1_rsq <- c(0.0037, 0.0726, 0.0847) 
> meta_rsq <- c(0.0263, 0.1829, 0.1753) 
> values <- c(pgc1_rsq, meta_rsq) 
> Type <- c(rep("PGC1", 3), rep("PGC meta-analysis", 3)) 
> mydata <- data.frame(p, values) 
> mydata$p <- factor(mydata$p, levels = c("5e-8", "0.05", "1")) 

我使用以下代碼創建的條形圖:

> plot <-ggplot(mydata, aes(p, values)) 
> plot +geom_bar(stat = "identity", aes(fill = Type), position = "dodge") + xlab("P-value threshold") + ylab("Proportion of variance explained (Nagelkerke Rsq)") 

哪個產生了這個陰謀: Bar plot

我現在想重新排列酒吧 - 以便「PGC1」在每對「PGC元分析」之前。我試圖讓這兩個「價值」和「類型」的因素和訂貨水平與PGC1未來第一是這樣的:

> mydata$value <- factor(mydata$value, levels = c("pgc1_rsq", "pgc_meta")) 

但是,這給了我一個錯誤消息「類型」,並沒有產生與「期望的結果值」。

輸入和建議將不勝感激。謝謝。

回答

1

爲什麼不包含在你的dataframeType

p <- rep(c("5e-8", "0.05", "1"), 2) 
pgc1_rsq <- c(0.0037, 0.0726, 0.0847) 
meta_rsq <- c(0.0263, 0.1829, 0.1753) 
values <- c(pgc1_rsq, meta_rsq) 
Type <- c(rep("PGC1", 3), rep("PGC meta-analysis", 3)) 
mydata <- data.frame(p, values,Type) 
mydata$Type <- factor(mydata$Type, levels = c("PGC1","PGC meta-analysis")) 
mydata$p <- factor(mydata$p, levels = c("5e-8", "0.05", "1")) 

plot <-ggplot(mydata, aes(p, values)) 
plot +geom_bar(stat = "identity", aes(fill = Type), position = "dodge") + xlab("P-value threshold") + ylab("Proportion of variance explained (Nagelkerke Rsq)") 
0

嘗試保填補geom_bar內:

plot <- ggplot(mydata, aes(p, values)) 
plot + geom_bar(stat = "identity", aes(fill = factor(Type, levels = c("PGC1", "PGC meta-analysis"))), position = "dodge") + 
xlab("P-value threshold") + 
ylab("Proportion of variance explained (Nagelkerke Rsq)") 
0

盪滌你的數據框有點

mydata <- data.frame(p = factor(rep(c("5e-8", "0.05", "1"), 2), levels = c("5e-8", "0.05", "1")), 
       values =c(0.0037, 0.0726, 0.0847, 0.0263, 0.1829, 0.1753), 
       Type = factor(c(rep("PGC meta-analysis", 3),rep("PGC1", 3)), levels = c("PGC1", "PGC meta-analysis"))) 



ggplot(mydata, aes(p, values))+ 
    geom_bar(stat = "identity", aes(fill = Type), position = "dodge") + 
    xlab("P-value threshold") + 
    ylab("Proportion of variance explained (Nagelkerke Rsq)") 
0

這些都是偉大的答案。最優雅的方式使用tidyr的非常有用的gather。必須在大多數ggplot s

library(dplyr) 
library(tidyr) 
library(ggplot2) 

data.frame(p = c("5e-8", "0.05", "1"), 
      `pgc1_rsq` = c(0.0037, 0.0726, 0.0847),     # change names here 
      `pgc_meta` = c(0.0263, 0.1829, 0.1753)) %>% 
    gather(Type, Value, 2:3) %>% 
    mutate(Type = factor(Type, levels = c("pgc1_rsq", "pgc_meta"))) %>% # and here if you need 
    ggplot(aes(x = p, y = Value, fill = Type)) + 
    geom_bar(stat = "identity", position = "dodge") + 
    xlab("P-value threshold") + 
    ylab("Proportion of variance explained (Nagelkerke Rsq)") 
+0

可能值得引入'tidyverse'因爲三個軟件包正在使用。 –

+0

我不喜歡堵塞我的名字空間,特別是在這樣的學習環境中,但對每個人來說都是如此。 – Zafar