简体   繁体   中英

How to make range plot in R?

Recently, I was tasked with creating a range plot in R. I thought it'd be easy, but to my surprise there was no geom_range() or anything like that. And with geom_bar the bars aren't used to starting from different locations.

I was able to make the following using geom_errorbar(), with the following sample code:

library("ggplot2")
d <- data.frame(sample=c("a","b","c"), middle=c(5,6,10), lower=c(2,4,7), upper=c(8,7,12))
ggplot() + geom_errorbar(data=d, mapping=aes(x=sample, ymin=upper, ymax=lower), width=0.2, size=1) + coord_flip()

在此处输入图像描述

But since error bars already have a clearly-defined purpose, I didn't want to use them going forward. I'd like to ensure I knew a better way. (Bonus points if I can do color transitions like in the example.)

Not sure about using a colour gradient on the lines, but here is one way of creating a 'range' plot:

library(tidyverse)
data <- tibble::tribble(~Education, ~Women, ~Men,
                        "Less than 9th grade", 21284, 34479,
                        "9th to 12 grade (no diploma)", 22472,  36837,
                        "High school graduate", 29119,  46833,
                        "Some college, no degree",  35499,  52852,
                        "Associate degree", 38149,  55795,
                        "Bachelor's degree",    54411,  84486,
                        "Master's degree",  69022,  99363,
                        "Doctorate",    90906,  151019
                        )
data$Education <- fct_reorder(data$Education, data$Women, .desc = TRUE)

data %>%
  ggplot(aes(x = Education)) +
  geom_linerange(aes(ymin = Women, ymax = Men, x = Education),
                 size = 1.5, alpha = 0.25) +
  geom_point(aes(y = Women), colour = "#CB5416") +
  geom_point(aes(y = Men), colour = "#267266") +
  coord_flip() +
  scale_y_continuous(labels = scales::dollar_format()) +
  ylab("Income") +
  theme_bw(base_size = 16) +
  theme(axis.title.y = element_blank())

示例_1.png

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