0
votes

How do I manipulate the x-axis in ggplot so that the 2020-July month corresponds(is labeled directly underneath) with the 1.4 and 2020-June month corresponds with 5.6 etc?

Here is the code:

ggplot(data, aes(x = month_end_date, y = average)) +
  geom_col(alpha = 0.6) +
  geom_text(aes(label = average), vjust = -0.5) +
  scale_x_date(breaks = '1 month', date_labels = '%Y-%m', expand =
c(.01, .01)) +
  theme_minimal() +
  theme(axis.text.x = element_text(angle = 90, vjust = .4)) +
  labs(fill = '', y = "")

plot

2
Could you paste in the code you used to produce that plot? Then we can see what instructions and parameters you have already provided to ggplot and better help you adjust them.Ben Norris
Your x data - date seems to be at the end of the month, thats whats causing it to shift. Try ggplot(data, aes(x = lubridate::floor_date(data$month_end_date, unit = "months"), y = average)) + ...SebSta
That helps. Now I can see that my proposed solution will likely work. You just need to add an appropriate hjust to your theme(axis.text.x = element_text(...)).Ben Norris
@SebSta, you have the right answer to OP's question. You should post it as an answer.chemdork123

2 Answers

0
votes

Without seeing your ggplot code, I cannot be certain what creates this issue, but a general solution to what you want is to use the + theme() function and set the hjust parameter for axis.text.x. Try a negative value for hjust to move the labels to the left. Try different values for hjust until you get what you want.

+ theme(axis.test.x = element_text(hjust = -0.5))

If you are using a predefined theme (either builtin or your own), make sure this line is after the application of that theme or this instruction will be overwritten by applying the theme.

0
votes

I got encouraged to post my advice from the comments as an answer:

The variablename "month_end_date" leads me to believe, that the date that is used is in fact some date at the end of the month. To get fitting bars over the months, you want your date to be the first of every month. This can be done easily with the library lubridate:

ggplot(data, aes(x = lubridate::floor_date(data$month_end_date, unit = "months"), y = average)) +
  geom_col(alpha = 0.6) +
  geom_text(aes(label = average), vjust = -0.5) +
  scale_x_date(breaks = '1 month', date_labels = '%Y-%m', expand = c(.01, .01)) +
  theme_minimal() +
  theme(axis.text.x = element_text(angle = 90, vjust = .4)) +
  labs(fill = '', y = "")