简体   繁体   中英

How to rotate the legend labels to match the orientation in the plot?

The legend labels are vertically oriented, but after the call to coord_flip() I would expect them to be horizontally oriented.

How can I fix this?

library(ggplot2)  
  
tbl <- structure(
  list(
    ppm_id = c(
      "PPM000001",
      "PPM000002",
      "PPM000014",
      "PPM000015",
      "PPM000050",
      "PPM000051",
      "PPM000084",
      "PPM000085"
    ),
    estimate_type_long = c(
      "Odds Ratio",
      "Odds Ratio",
      "Hazard Ratio",
      "Hazard Ratio",
      "Hazard Ratio",
      "Hazard Ratio",
      "Hazard Ratio",
      "Relative Risk "
    ),
    estimate = c(1.55, 1.63, 1.21, 1.14, 1.17,
                 1.24, 1.17, 1.2),
    interval_lower = c(1.52, 1.6, 1.17, 1.02, 1.13,
                       1.15, 1.01, 1.05),
    interval_upper = c(1.58, 1.67, 1.26, 1.28,
                       1.21, 1.34, 1.34, 1.38)
  ),
  row.names = c(NA, -8L),
  class = c("tbl_df",
            "tbl", "data.frame")
)

ggplot(data = tbl,
       aes(
         x = ppm_id,
         y = estimate,
         ymin = interval_lower,
         ymax = interval_upper,
         col = estimate_type_long
       )) +
  geom_pointrange() +
  geom_hline(yintercept = 1, lty = 2) +  # add a dotted line at x=1 after flip
  coord_flip() +  # flip coordinates (puts labels on y axis)
  xlab("Label") + ylab("Mean (95% CI)") +
  theme_bw()  # use a white background

Created on 2021-05-21 by the reprex package (v2.0.0)

One workaround is to use point and error bar layers instead of geom_pointrange() . Error bars have horizontal line key glyphs where pointrange has vertical lines in the keys.

Use width = 0 in geom_errorbar() to get rid of the end bars. You'll need to fiddle with the point size here to make them "fatter" (the pointrange layer has a fatten argument for this); I thought size = 2 looked close.

ggplot(data = tbl,
       aes(
           x = ppm_id,
           y = estimate,
           ymin = interval_lower,
           ymax = interval_upper,
           col = estimate_type_long
       )) +
    geom_point(size = 2) +
    geom_errorbar(width = 0) +
    # geom_pointrange() +
    geom_hline(yintercept = 1, lty = 2) +  # add a dotted line at x=1 after flip
    coord_flip() +  # flip coordinates (puts labels on y axis)
    xlab("Label") + ylab("Mean (95% CI)") +
    theme_bw()  # use a white background

Created on 2021-05-21 by the reprex package (v2.0.0)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM