move the labels on y-axis inside the plot

Advertisements

The data is:

df <- structure(list(country = c("Italy", "Switzerland", "Sweden", 
                       "Netherlands", "England", "Poland", "Russia", "Czech", "Hungary", 
                       "Turkey"), `0.025quant` = c(-2.98, 2.02, 1.02, 0.02, 3.02, -2.98, 
                                                   -0.98, -1.98, -1.98, -0.98), mean = c(-2, 3, 2, 1, 4, -2, 0, 
                                                                                         -1, -1, 0), `0.975quant` = c(-1.02, 3.98, 2.98, 1.98, 4.98, -1.02, 
                                                                                                                      0.98, -0.02, -0.02, 0.98)), class = c("tbl_df", "tbl", "data.frame"
                                                                                                                      ), row.names = c(NA, -10L))

Which I plot as:

plot <- ggplot(data = df, aes(x = mean, y = country)) + geom_point() + geom_errorbarh(aes(xmin = 0.025quant, xmax = 0.975quant), height = .1) + geom_vline(xintercept = 0, linetype = 2) + scale_x_continuous(breaks = seq(-3, 5, 1))

I am trying to move the labels on y-axis (countries’ name, circled with blue marker in the picture below) inside the plot, so it would get located to the right and above its original default position, slightly above the white line. In the picture below, I wrote the desired outcome with the red marker, indicating where the names of all countries have to go.

Could you help me out with this, guys?

>Solution :

You could use a geom_text or what I would prefer a geom_label to fake your desired inside axis text, then remove the axis text using element_blank():

library(ggplot2)

ggplot(data = df, aes(x = mean, y = country)) + 
  geom_point() + 
  geom_errorbarh(aes(xmin = `0.025quant`, xmax = `0.975quant`), height = .1) + 
  geom_vline(xintercept = 0, linetype = 2) + 
  geom_label(
    data = ~ dplyr::distinct(.x, country),
    aes(x = -3.5, label = country),
    hjust = 0,
    vjust = 0,
    fill = NA,
    label.size = 0
  ) +
  scale_x_continuous(breaks = seq(-3, 5, 1), expand = c(0, 0, .05, 0)) +
  theme(axis.text.y = element_blank()) +
  coord_cartesian(clip = "off")

Leave a ReplyCancel reply