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

move the labels on y-axis inside the plot

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.

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

enter image description here

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")

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