2015-08-15 22 views
1

我有ggplot中的幾列數據我希望繪製在boxplot中。每個方框代表一列數據。這些箱子應該以四個一組(紅,綠,藍,黃)着色,即每2盒被染成綠色每四個被標記爲黃色等ggplot中的着色boxplot列以重複模式

樣本數據

X1 X1.1 X1.2 X1.3 X2 X2.1 X2.2 X2.3 
1 2 3 4 3 2 3 1 
2 4 5 5 5 2 1 2 
2 3 2 1 2 1 2 5 

我得到的最接近使用重複的顏色值填充矢量colorVec並嘗試將其應用於ggplot。

graph<-ggplot(expressionframemelted, aes(x = Var2, y=value)) +  
geom_boxplot(aes(fill = factor(Var2)))+ 
ggtitle("Expression Values and Medians")+xlab(valueAmountsP)+ylab("Counts log 10")+ 
stat_summary(fun.y = median, geom = "point", position = position_dodge(width = .9), 
size = 6, shape = 4, show_guide = F)+ 
theme(axis.text.x=element_text(angle=90))+ 
scale_x_discrete(labels=nameVecGraph)+ 
scale_y_log10()+ 
scale_fill_manual(values = colorVec) 

的問題是,如果列值是非常低或零到一箱未對劇情ggplot由於某種原因出現使用填充他們跳過,並繼續到下一個塔的點擰緊着色的順序。

任何更簡單的方法呢?

編輯:我試過epi的答案,但ggplot跳過低值的列和混亂的顏色順序的問題依然存在。我發現這可能是由於使用了對數刻度。例如嘗試

ggplot(dfmelt, aes(variable, value, fill=variable)) + 
geom_boxplot() + 
theme(axis.text.x=element_text(angle=90))+ 
scale_x_discrete(labels=c('C1','C2','C3','C4','C5','C6','C7','C8'))+ 
scale_y_log10()+ 
scale_fill_manual(values=rep(c("red","green","blue","yellow"),2)) 

df = read.table(text="X1 X1.1 X1.2 X1.3 X2 X2.1 X2.2 X2.3 
      1 0 3 4 3 2 3 1 
      2 'NA' 5 5 5 2 1 2 
      2  'NA' 2 1 2 1 2 5", header=TRUE) 

回答

2

怎麼是這樣的:

df = read.table(text="X1 X1.1 X1.2 X1.3 X2 X2.1 X2.2 X2.3 
1 2 3 4 3 2 3 1 
2 4 5 5 5 2 1 2 
2 3 2 1 2 1 2 5", header=TRUE) 

library(reshape2) 
library(dplyr) 
library(ggplot2) 

ggplot(df %>% melt(), aes(variable, value, fill=variable)) + 
    geom_boxplot() + 
    scale_fill_manual(values=rep(c("red","green","blue","yellow"),2)) 

enter image description here

如果你讓你的代碼reproducible(在這種情況下,這將意味着提供一個可以與您發佈的代碼一起工作的數據樣本)我可以定製我的答案更直接地回答你的問題。

更新:在回答您編輯的問題和您的意見:ggplot不繪製更新數據集的第二列,因爲它不包含正值。在對數變換下,零點變爲-Inf,負值變爲NA(對於實數),所以沒有什麼可以繪圖,並且ggplot在分配顏色時會跳過或放棄該x值。要保持着色順序,請將drop=FALSE添加到scale_fill_manual

ggplot(dfmelt, aes(variable, value, fill=variable)) + 
    geom_boxplot(show_guide=FALSE) + 
    theme(axis.text.x=element_text(angle=90, vjust=0.5)) + 
    scale_x_discrete(labels=c('C1','C2','C3','C4','C5','C6','C7','C8')) + 
    scale_y_log10(breaks=1:5) + 
    scale_fill_manual(values=rep(c("red","green","blue","yellow"),2), drop=FALSE) 

enter image description here

+0

喜的是%>%? Rstudio咳嗽它,我試圖在谷歌上查找它,但我找不到它。 –

+1

我的不好;我忘了在我的代碼中包含'dplyr'軟件包。我現在修好了。 '%>%'是一個允許你將功能鏈接在一起的運算符。參見['dplyr' vignette](https://cran.rstudio.com/web/packages/dplyr/vignettes/introduction.html)。如果您想避免在ggplot調用中執行此操作,可以將數據融化爲ggplot外的長格式。只要執行'df.melt = melt(df)',然後在ggplot中使用'df.melt'而不是'df'。 – eipi10

+1

嗨,問題是如果我使用日誌10規模ggplot將出於某種原因跳過低價值列擰緊顏色的順序。看看編輯 –