U W
U W

Reputation: 1290

ggplot: Centre and move the vertical axis labels

I'm looking to set up a mirrored bar chart with one set of axis labels in the middle. This image shows what I have so far (code to reproduce at the end):

enter image description here

I'd like the names to be centred between the charts. Methods tried:

I'd welcome any suggestions around the easiest way to achieve this layout. The base has to be ggplot, but happy to use other packages to arrange charts.

require("ggplot2")
require("gridExtra")

dataToPlot <- data.frame(
  "Person" = c("Alice", "Bob", "Carlton"),
  "Age" = c(14, 63, 24),
  "Score" = c(73, 62.1, 21.5))

plot1 <- ggplot(dataToPlot) +
  geom_bar(data = dataToPlot, aes(x = Person, y = Score), stat = "identity",
    fill = "blue", width = 0.8) +
  scale_y_continuous(trans = "reverse", expand = c(0, 0)) +
  scale_x_discrete(position = "top") +
  theme(
    axis.text.y = element_blank()
  ) +
  labs(x = NULL) +
  coord_flip()

plot2 <- ggplot(dataToPlot) +
  geom_bar(data = dataToPlot, aes(x = Person, y = Age), stat = "identity",
    fill = "red", width = 0.8) +
  scale_y_continuous(expand = c(0, 0)) +
  theme(
    axis.text.y = element_text(size = 20, hjust = 0.5)
  ) +
  labs(x = "") +
  coord_flip()

gridExtra::grid.arrange(plot1, plot2, ncol = 2, widths = c(1, 1.2))

Upvotes: 2

Views: 4301

Answers (1)

Andrew Gustar
Andrew Gustar

Reputation: 18425

There are two ways (perhaps in combination)...

Add a margin to the right of the axis labels in the right-hand chart...

element_text(size = 20, hjust = 0.5, margin=margin(r=30))

...or move the two charts closer together

grid.arrange(plot1, plot2, ncol = 2, widths = c(1, 1.2),padding=0)

Upvotes: 4

Related Questions