Change position of number of bar (ggplot) with negative and positive values

Viewed 142

I have the next code, where I have negative positive and negative values and I want to put the positive values above the edge of bar, and negative values below the edge of the bar. I want to know too how to change the y axes (limites), changes the order of "Flujo" and how to change background graph.

tabla <-
   Flujo         Mes Valor
1    Qns  Septiembre  79.4
2    Qnl  Septiembre -97.5
3     Qh  Septiembre  -3.1
4     Qe  Septiembre -11.3
5     Qr  Septiembre   0.5
6     Qg  Septiembre  16.5
7     Qm  Septiembre  15.5
8    Qns     Octubre  79.1
9    Qnl     Octubre -87.8
10    Qh     Octubre  -0.8
11    Qe     Octubre  -1.7
12    Qr     Octubre   0.0
13    Qg     Octubre  36.0
14    Qm     Octubre -57.9


tabla<-data.frame("Flujo"=c("Qns","Qnl","Qh","Qe","Qr","Qg","Qm","Qns","Qnl","Qh","Qe","Qr","Qg","Qm"),
                  "Mes"= rbind(array(" Septiembre", dim=c(7,1))   , array("Octubre", dim=c(7,1)))  ,
                  "Valor"=round(c(s1$Qns,s1$Qnl,s1$Qh,s1$Qe,s1$Qr,s1$Qg,s1$Qm,s2$Qns,s2$Qnl,s2$Qh,s2$Qe,s2$Qr,s2$Qg,s2$Qm),digits=1))



colors <-c("Qns"="red","Qnl"="blue","Qh"="deeppink","Qe"="darkgoldenrod1","Qr"="darkblue","Qg"="green","Qm"="brown")


fig31 <- ggplot(data=tabla, aes(x=Mes, y=Valor,fill=Flujo)) +
  geom_bar(stat="identity", color="black", position=position_dodge())+
  theme_minimal()+
  geom_text(aes(label=Valor),position=position_dodge(width=0.9),size=4, vjust=1.5)+
  scale_fill_manual(values = colors) + 
  theme_light()
  
fig31
1 Answers

Here is one way you could do: I changed geom_bar with geom_col anc put an ifelse in geom_text(). Here you can define the position 0,-1,1.5` of the numbers.

fig31 <- ggplot(tabla, aes(Mes, Valor, fill=Flujo)) +
   geom_col(position = position_dodge()) +
   geom_text(aes(label = paste(Valor)),
                 position=position_dodge(width=0.9),size=3,
                 vjust = ifelse(tabla$Valor >= 0, -1, 1.5)) +
   scale_fill_manual(values = colors) +
   theme_light()

fig31
 

enter image description here

Related