Danny_0101
Danny_0101

Reputation: 83

How to format R Bar Plot to Centre bars with axis labels

So I've plotted quarterly data for 6 years, but I'm having trouble trying to get the bars in the plot to line up with the yearly labels. It's purely an aesthetic problem. Just wondering if there is a way to centre them?

I have tried adding the following code which I found but this doesn't seem to work;

axis(1,at=barposition,labels=names(x),padj=1)

The code I have used to make the graph thus far is;

data001 %>%
  mutate(Q = lubridate::quarter(date001, with_year = T)) %>%
  group_by(Q) %>% 
  summarize(Antibiotic_by_Q = sum(Antibiotic.Cow)) %>% 
  ggplot(aes(Q, Antibiotic_by_Q)) + 
       geom_bar(stat = "identity", fill = "salmon2") +
       scale_x_yearqtr(format = "%Y") + 
       ylab("Antibiotic Total (Grams)") + 
       xlab("Date (Quarters/Year)")

Any help with code that might help centre the bar plots would be much appreciated! :)

1

Upvotes: 1

Views: 972

Answers (1)

PavoDive
PavoDive

Reputation: 6496

You're very close. To your ggplot call, add:

theme(axis.text.x = element_text(hjust = 0.5))

hjust stands for horizontal justificatioṇ, and accepts values between 0 (left) and 1 (right). You may be interested in vjust too, see ?element_text

Upvotes: 1

Related Questions