Home > Enterprise >  Align the x-axis labels with the bars in R
Align the x-axis labels with the bars in R

Time:06-28

I have a data set like that :

Vente Nombre
Vente 679
Vente en l'état futur d'achèvement 137

I used the following code :

g1 <- ggplot(data=df, aes(x = libnatmut, y = counts, fill=libnatmut))  
  geom_bar(stat = "identity", width = 0.3, position=position_dodge2(preserve='single')) 
  labs(title = "Nature des mutations", x="Type de la vente",y="Nombre de ventes")  
  geom_text(aes(label = counts), vjust = -0.3)  
  theme(axis.text.x = element_text(angle = 17, hjust = 1))   
  theme(axis.text.x = element_text(face="bold", color="#993333",size=14, angle=0),
        axis.text.y = element_text(face="bold", color="#993333",size=14, angle=360),
        axis.title=element_text(size=22)) 
  theme(plot.title = element_text(size=24)) 
  theme(axis.line = element_line(colour = "#993333", 
                                 size = 1, linetype = "solid")) 
  scale_fill_manual(values= rep_len(wes_palette("Zissou1"), 10)) 
  theme(legend.position="none")

ggsave(g1, filename = "libnatmut.png", dpi = 300, height = 30, width = 30, units = "cm")

As we can see on the chart, the x-axis labels aren't aligned with my bars. I tried a lot of different things, but I can't manage to obtain a centered chart. enter image description here

It's probably pretty easy, but I only used R a long time ago so I'm not an expert at all with ggplot2.

CodePudding user response:

I modified the ggplot code a litte and used the data provided.

  • Main action was to remove: theme(axis.text.x = element_text(angle = 17, hjust = 1))
library(wesanderson)
library(tidyverse)

ggplot(data=df, aes(x = Vente, y = Nombre, fill=Vente))  
  geom_bar(stat = "identity", width = 0.3, position=position_dodge2(preserve='single')) 
  labs(title = "Nature des mutations", x="Type de la vente",y="Nombre de ventes")  
  geom_text(aes(label = Nombre), vjust = -0.3)  
  theme(axis.text.x = element_text(face="bold", color="#993333",size=14, angle=0),
        axis.text.y = element_text(face="bold", color="#993333",size=14, angle=360),
        axis.title=element_text(size=22)) 
  theme(plot.title = element_text(size=24)) 
  theme(axis.line = element_line(colour = "#993333", 
                                 size = 1, linetype = "solid")) 
  scale_fill_manual(values= rep_len(wes_palette("Zissou1"), 10)) 
  theme(legend.position="none")

enter image description here

data:

df <- structure(list(Vente = c("Vente", "Vente en l'état futur d'achèvement"
), Nombre = c(679L, 137L)), class = "data.frame", row.names = c(NA, 
-2L))
  • Related