2013-03-09 73 views
1

我試圖繪製R.使用ggplot圖這裏是我的代碼:ggplot條形圖額外的空間

library(reshape2) 
library(ggplot2) 
dfw <- read.table(header=T, text=' 
    Length L1 L2 
    200:399  27665 28483 
    400:599  9232 11856 
    600:799  3347 4072 
    800:999  1923 2112 
    1000:1199 1322 1511 
    1200:1399 955 1118 
    1400:1599 693 850 
    1600:1799 496 640 
    1800:1999 332 463 
    2000:2199 219 306 
    2200:2399 142 212 
    2400:2599 73 134 
    2600:2799 65 121 
    2800:2999 39 87 
    3000:3199 19 57 
    3200:3399 20 31 
    3400:3599 14 37 
    3600:3799 4 22 
    3800:3999 2 17 
    4000:9599 8 53 
') 

data.long <- melt(data = dfw, id.var = "Length", 
       measure.vars = c("L1", "L2"), variable.name = "Condition") 

ggplot(data=data.long, aes(x=Length, y=value, fill=Condition)) + 
     geom_bar(stat="identity", position=position_dodge(width = 1), 
     colour="black", na.rm = TRUE, width = 0.5) + 
     scale_x_discrete(limits = data.long$Length) + 
     theme(axis.title.x = element_text(face="bold", colour="#990000", size=20), 
     axis.text.x = element_text(angle=90, vjust=2, size=16)) 

ggplot2_my_plot

我的問題是,無論我怎麼努力,我無法擺脫繪圖區域的額外空間。任何建議將不勝感激。

+0

你在這裏設置了限制:'scale_x_discrete(limits = data.long $ Length)'。你嘗試刪除它嗎? – Arun 2013-03-09 19:32:15

+0

是的,然後重新排列x軸。 – user690462 2013-03-09 19:36:57

回答

2

在你的代碼的主要問題是,有在水平的順序錯誤變量Length。 您可以使用函數factor()和參數levels=dfw$Length修復它(因爲您的原始數據幀的順序是正確的)。

data.long$Length<-factor(data.long$Length,levels=dfw$Length) 

現在您不需要使用scale_x_discrete()來設置限制。

ggplot(data=data.long, aes(x=Length, y=value, fill=Condition)) + 
    geom_bar(stat="identity", position=position_dodge(width = 1), colour="black", na.rm = TRUE, width = 0.5) + 
    theme(axis.title.x = element_text(face="bold", colour="#990000", size=20), 
     axis.text.x = element_text(angle=90, vjust=2, size=16)) 
+0

太棒了,它像一個魅力。非常感謝。 – user690462 2013-03-09 19:47:06

1

刪除此scale_x_discrete(limits = data.long$Length),然後再試一次希望這有助於

編輯:通過刪除該刪除在Y,如果你有它scale_y_discrete(limits = data.long$Length)

+0

我試過了,但它重新排列了x軸。 – user690462 2013-03-09 19:36:31