2013-01-22 193 views
1

數據鏈接: https://www.dropbox.com/s/ql5jw7eng3plrso/GTAP_MacroValueChange.csvggplot堆疊barplot

代碼:在手

library(ggplot2) 
    library(grid) 

    #Upload data 
    ccmacrosims2 <- read.csv(file = "F:/Purdue University/RA_Position/PhD_ResearchandDissert/PhD_Draft/GTAP-CGE/GTAP_NewAggDatabase/NewFiles/GTAP_MacroValueChange.csv", header=TRUE, sep=",", na.string="NA", dec=".", strip.white=TRUE) 

    #Data manipulation for analysis 
    ccmacrorsts2 <- as.data.frame(ccmacrosims2) 
    ccmacrorsts2[6:10] <- sapply(ccmacrorsts2[6:10],as.numeric) 
    ccmacrorsts2 <- droplevels(ccmacrorsts2) 
    ccmacrorsts2 <- transform(ccmacrorsts2,region=factor(region,levels=unique(region))) 

    #Selecting data of interest 
    GDPDecomp1 <- melt(ccmacrorsts2[ccmacrorsts2$region %in% c("TUR","MAR"), ]) 
    GDPDecomp2 <- GDPDecomp1[GDPDecomp1$sres %in% c("AVERAGE"), ] 
    GDPDecomp.f <- subset(GDPDecomp2, variable !="GDP") 

    #Ploting 
    GDPDecompPlot <- ggplot(data = GDPDecomp.f, aes(factor(region),value, fill=variable)) 
    GDPDecompPlot + geom_bar(stat="identity", position="stack") + facet_wrap(~tradlib, scales="free_y") + 
    theme(axis.text.x = element_text(colour = 'black', angle = 90, size = 12, hjust = 0.5, vjust = 0.5),axis.title.x=element_blank()) + 
    ylab("GDP (Change in $US million)") + theme(axis.text.y = element_text(colour = 'black', size = 12), axis.title.y = element_text(size = 12)) + 
    theme(strip.text.x = element_text(size = 12, hjust = 0.5, vjust = 0.5, face = 'bold')) 

問題: 使用ggplot(見下文)的barplot ggplot_barplot

excel_barplot: excel_barplot_sample

它的eems該情節並不真正代表數據的價值。我正在尋找的是類似於我們從excel_barplot_sample中獲得的東西。例如,比較ggplot下的面板「TRLIBEU」和使用excel的面板「TRLIBEU」,可以清楚地注意到ggplot在堆疊時沒有正確捕獲數據中的值。

有關如何糾正差異的任何幫助?

在此先感謝

+0

如果負的數據值導致了問題,那麼你真的應該提高對GGPLOT2錯誤的警告消息。人們究竟會如何檢測到這種情況? – smci

回答

4

如果需要使用負值堆疊酒吧ggplot2然後更好的結果,你應該做兩個新的數據幀 - 一個用於正面的價值觀和第二負值。

GDPDecomp.f.pos<-GDPDecomp.f[GDPDecomp.f$value>0,] 
GDPDecomp.f.neg<-GDPDecomp.f[GDPDecomp.f$value<0,] 

然後在自己的geom_bar()調用中使用每個數據幀。

ggplot()+ 
    geom_bar(data=GDPDecomp.f.pos,aes(x=factor(region),y=value,fill=variable),stat="identity")+ 
    geom_bar(data=GDPDecomp.f.neg,aes(x=factor(region),y=value,fill=variable),stat="identity")+ 
    facet_wrap(~tradlib, scales="free_y") + 
    theme(axis.text.x = element_text(colour = 'black', angle = 90, size = 12, hjust = 0.5, vjust = 0.5),axis.title.x=element_blank()) + 
    ylab("GDP (Change in $US million)") + theme(axis.text.y = element_text(colour = 'black', size = 12), axis.title.y = element_text(size = 12)) + 
    theme(strip.text.x = element_text(size = 12, hjust = 0.5, vjust = 0.5, face = 'bold')) 

enter image description here

+0

非常感謝:D – iouraich