2017-05-10 108 views
2

我有以下數據集,爲此我使用'ggplot2'生成了堆積條形圖。R ggplot2 bar等效於R基圖

數據 - >

X1 X2 X3 
1 1 10 13.53 
2 1 10 16.81 
3 2 10 16.24 
4 2 10 17.42 
5 1 10 15.20 
6 1 10 29.40 
7 1 10 45.30 
8 1 10 14.00 
9 1 10 23.50 
10 2 10 12.30 

GGPLOT2代碼--->

ggplot(data=dat1, aes(x=X2, y=X3, fill=X1,width=0.5)) + 
    geom_bar(stat="identity") + coord_flip() + 
    theme(legend.position="bottom",legend.direction="horizontal",legend.text=element_text(size=12), 
     plot.margin=unit(c(0.1,1,0.25,1), "cm"), 
     panel.grid.major = element_blank(), panel.grid.minor = element_blank(),axis.title.y=element_blank(), 
     axis.text.y=element_blank(), 
     axis.ticks.y=element_blank())+ 
    guides(fill=guide_legend(nrow=1,byrow=TRUE)) + 
    scale_x_continuous(breaks = 10)+ 
    scale_y_continuous(breaks=c(seq(0,sum(dat1$X3),50),sum(dat1$X3)),expand = c(0,0))+ 
    labs(fill="") 

我想現在使用barplot()R的函數,這樣我將其轉換成R基本情節可以在別的地方使用它。我無法使用基本barplot函數生成堆積條形圖,我必須使用單列但是使用2組進行堆疊。

感謝您的幫助。

+0

爲什麼你不能在其他地方使用ggplot barplot? – user3640617

+0

@ user3640617:我需要與另一個R圖(時間序列)結合使用,以便在組合時遇到問題。所以作爲一個替代方案,我想在R基地中做出這兩個情節。 –

回答

2

也許這可以幫助你

X1=c(1,1,2,2,1,1,1,1,1,2) 
X2=rep(10,10) 
X3=c(13.53,16.81,16.24,17.42,15.20,29.40,45.30,14.00,23.50,12.30) 

my.color<-rev(c("#4292C6","#08306B")) 

# this is the important thing, to pass your data into barplot as a matrix 
dat1<-as.matrix(X3,X2) 

barplot(dat1,col = my.color[as.factor(X1)],border = my.color[as.factor(X1)], 
     beside = FALSE,horiz=TRUE, 
     xaxt="n",yaxt="n",xlab="",ylab="",main="") 

axis(1, at=seq(0,sum(X3),by=50)) 
axis(2, at=0.7,labels = 10) 
legend(0,1.4, fill=my.color, legend=c(1, 2))  

結果如下:

enter image description here

爲了添加傳說敵人的陰謀,你也許將不得不改變XPD選項在par()從FALSE到TRUE:

par(xpd=TRUE) 

希望它有幫助。

+0

非常感謝..這有助於我.. –