nit
nit

Reputation: 689

Horizontal barplot with negative values issue

I have following data

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

I have this code:

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

This code gave the plot as follows

enter image description here

This plot has problem bars are on right side but it should be towards left and x axis should start 0 to -10. Can any body to suggest soultions for this problem

Upvotes: 2

Views: 938

Answers (1)

LyzandeR
LyzandeR

Reputation: 37889

I know that ggplot cannot handle horizontal bars well when the values are negative (this is why the rotated image goes from the left to right). The following is pretty much a hack to get what you need, but there might be a better way:

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

Output:

enter image description here

Upvotes: 3

Related Questions