2013-07-25 17 views
1

我想繪製特定疾病患者樣本的某些臨牀特徵。有四個變量是二分法的,如果它們中的任何一個對於侵略性爲真,那麼患者被標記爲具有侵略性的過程。 一次只做一個變量意味着我們可以使用堆積或閃避的條形圖。我們甚至可以使用餅圖。 但是要顯示所有變量和單個圖表上的組合更具挑戰性。您如何繪製一系列二分變量和複合變量

我創建了一些虛擬數據(只有三個特徵+複合)。我無法相信我必須通過多少操作才能將這些數據繪製成我想要的內容。我遇到了每一個存在的問題。每個問題需要更多的操作。當我查找答案(例如在stackoverflow上)時,我什麼都找不到,可能是因爲我不知道什麼是流行語來描述我正在嘗試做什麼。

問題
1)什麼是對的流行詞彙什麼,我試圖做
2)是否真的需要這麼難,還是有在GGPLOT2更直接的途徑,它可以讓我直奔圖表從原始數據文件,其中包含儘可能多的行,因爲有人類受試者

創建了一些模擬數據

require(data.table) 
aggr.freq <- sample(c(TRUE, FALSE), size=100, replace=TRUE, prob=c(0.1, 0.9)) 
aggr.count <- sample(c(TRUE, FALSE), size=100, replace=TRUE, prob=c(0.2, 0.8)) 
aggr.spread <- sample(c(TRUE, FALSE), size=100, replace=TRUE, prob=c(0.4, 0.6)) 
human.subjects <- data.table(aggr.freq, aggr.count, aggr.spread) 
human.subjects[,aggr.course.composite:=aggr.freq|aggr.count|aggr.spread] 

理貨的trues

aggr.true <- human.subjects [,list(aggr.freq = sum(aggr.freq), aggr.count = sum(aggr.count), aggr.spread = sum(aggr.spread), aggr.course.composite= sum(aggr.course.composite))] 

這一紀錄是在錯誤的方向密謀

aggr.true.vertical <- data.table(t(aggr.true)) 
aggr.true.vertical[,clinical.characteristic:=factor(dimnames(t(aggr.true))[[1]], ordered=TRUE, levels= c("aggr.freq", "aggr.count", "aggr.spread", "aggr.course.composite"))]#have to specify levels otherwise ggplot2 will plot the variables in alphabetical order 
setnames(x=aggr.true.vertical, old = "V1", new = "aggressive") 
aggr.true.vertical[,indolent:=human.subjects[,.N]-aggressive]#we had the tally of trues now we need to tall the falses 


ggplot(aggr.true.vertical, aes(x=clinical.characteristic, y=aggressive)) + geom_bar(stat="identity") # alas, this graph only shows the count of those with an aggressive characteristic and does not give the reader a feel for the proportion. 

重塑第二次

require(reshape2) 
long <- melt(aggr.true.vertical, variable.name="aggressiveness",value.name="count") 
ggplot(long, aes(x=clinical.characteristic, y=count, fill=aggressiveness)) + geom_bar(stat="identity") 

感謝。

+1

如果你要使用data.table語法,你應該包括'庫(data.table)'因爲你的第一道防線。 –

回答

2

我想我可以看到你在思考問題的過程中發生了什麼,但是我認爲你在這個過程的早期就「走錯了路」。我不確定我可以幫助您使用關鍵字進行搜索。無論如何,所有你需要的是一個融化,然後你可以陰謀。您的數據生成後:

human.subjects$id<-1:nrow(human.subjects) # Create an id variable (which you probably have) 
melted.humans<-melt(human.subjects,id='id') 
ggplot(melted.humans, aes(x=variable,fill=value)) + geom_bar() 

enter image description here

也許你寧願翻轉真假的順序,但你的想法。

另外,您可能會對一些簡化的代碼感興趣,這些代碼用於您正在做的其他部分,這些代碼用於計算trues和falses。 (在我的解決方案,我只是讓ggplot做到這一點。)

# Count the trues: 
sapply(human.subjects,sum) 

# Collect all the trues and falses into a single matrix, 
# by running table on each column. 
sapply(human.subjects,table)