2
votes

I have following data set for which I have generated stacked bar plot using 'ggplot2'.

Data -->

    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 code --->

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="")

I want to now convert it into R base plot using barplot() function of R so that I can use it somewhere else. I am unable to generate the stacked bar plot using the base barplot function which i have to stack using single column but 2 groups.

Thanks for the help.

1
Why can't you use the ggplot barplot somewhere else? - user3640617
@user3640617 : I need to combine with another R plot(time series) with which i am having trouble in combining. So as an alternative i wanted to make both in R base plot. - Anish Sharma

1 Answers

2
votes

maybe this can help you

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))    

The result is the following:

enter image description here

In order to add the legend out of the plot you maybe will have to change the xpd option in par() from FALSE to TRUE:

par(xpd=TRUE)

Hope it helps.