2015-11-21 94 views
2

我有以下數據負值問題水平barplot

d1 d2 
a -9.278 
b -5.582 
c -5.266 
d -5.01 
e -3.833 

我有這樣的代碼:

library(ggplot2) 

dat<-read.csv("input.csv",sep=",") 
dat1<-dat[,-3] 

ggplot(dat11,aes(x = d1, y = d2)) + 
geom_bar(fill="#e34a33",width=0.34,stat="identity") + 
scale_x_discrete(limits=dat1$d1) + 
    coord_flip() + 
    theme_bw() + theme(legend.position = "none", panel.grid.major=element_blank(), 
        panel.grid.minor=element_blank(),legend.key = 
element_blank(),axis.title.x = element_text(size=15),axis.text.x = 
element_text(size=16), axis.title.y = 
element_text(size=15),axis.text.y=element_text(size=17), 
panel.border = element_rect(colour = "black",size=0.7)) 

此代碼給了情節如下

enter image description here

此圖問題欄在右側,但應該朝左,x軸應該開始0到-10。任何機構可以建議這個問題的靈魂提示

回答

3

我知道ggplot不能很好地處理水平酒吧當值爲負(這就是爲什麼旋轉的圖像從左到右)。得到你所需要的下面是一個很值得破解,但有可能是一個更好的辦法:

#I start by converting y into positive numbers 
ggplot(dat11,aes(x = d1, y = d2*(-1))) + 
    geom_bar(fill="#e34a33",width=0.34,stat="identity") + 
    #then I use scale_y_continuous to specify the breaks i.e. the ticks to appear 
    #and also use labels to label them as negative numbers 
    #everything else stayed the same 
    scale_y_continuous(breaks = c(0, 2.5, 5.0, 7.5, 10), labels = c('0', '-2.5', '-5.0', '-7.5', '-10')) + 
    coord_flip(ylim = c(0, 10)) + 
    theme_bw() + theme(legend.position = "none", panel.grid.major=element_blank(), 
        panel.grid.minor=element_blank(),legend.key = 
         element_blank(),axis.title.x = element_text(size=15),axis.text.x = 
         element_text(size=16), axis.title.y = 
         element_text(size=15),axis.text.y=element_text(size=17), 
        panel.border = element_rect(colour = "black",size=0.7)) 

輸出:

enter image description here

+1

豈不是不夠加上'scale_y_reverse'到OP中的代碼? – Henrik

+0

謝謝@Henrik是的,它實際上更好。 'coord_flip(ylim = c(-10,0))''''scale_y_reverse()'這個技巧。如果我是你,我會添加它作爲一個新的答案:) – LyzandeR