Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Adjusting alignment of bars to x-axis labels in ggplot

I wrote the code below which works without errors but the two bars are not aligned with x-axis labels "pre" and "post." I have tried incorporating the solution here but it does not seem to fix the misalignment issue in my case.

dput(collective_action_mentions[1:2, c(1,2,3,4)])

output:

structure(list(treatment_implementation = c(0, 1), total_posts = c(2055L, 
866L), collective_count = c(77L, 22L), collective_share = c(3.74695863746959, 
2.54041570438799)), row.names = c(NA, -2L), class = c("tbl_df", 
"tbl", "data.frame"))

graph code:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

ggplot(data = collective_action_mentions, aes(x = treatment_implementation, fill=treatment_implementation,  y = collective_share)) +
    geom_bar(stat = "identity", position=position_dodge()) + 
    ylab("% Share of collective action mentions") + 
    theme(text=element_text(size=10)) +
    scale_x_discrete(limits = c("pre", "post"))+
  labs(fill='Policy implementation')+ 
      xlab("Period")  +
    theme(plot.title = element_text(size = 10, face = "bold")) 

enter image description here

>Solution :

If you are using scale_x_discrete, then your x value should be a factor, not numeric. And then you just need to set the labels=, not the limits=

ggplot(data = collective_action_mentions, aes(x = factor(treatment_implementation), fill=treatment_implementation,  y = collective_share)) +
  geom_bar(stat = "identity", position=position_dodge()) + 
  ylab("% Share of collective action mentions") + 
  theme(text=element_text(size=10)) +
  scale_x_discrete(labels = c("pre","post"))+
  labs(fill='Policy implementation')+ 
  xlab("Period")  +
  theme(plot.title = element_text(size = 10, face = "bold")) 

enter image description here

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading