简体   繁体   中英

How create horizontal plots with colorized cells in R?

I have the following data set (test) and would like to create a horizontal bar plot with "cells" of different colors depending on the "variable" values. For example, "A" in red, "B" in blue, and "C" in gray colors. The end plot should look like a "colorized stack progress bar". Thanks!

"","date_obs","variable"
"1",2021-01-06,"C"
"2",2020-11-04,"C"
"3",2020-10-27,"B"
"4",2020-07-02,"C"
"5",2019-09-04,"B"
"6",2019-08-07,"C"
"7",2019-05-08,"B"
"8",2019-03-13,"B"
"9",2018-10-12,"A"
"10",2017-12-12,"A"

Is this what you had in mind?

I've assumed the first row item extends to today's date.

library(tibble)
library(dplyr)
library(lubridate)
library(ggplot2)


tib1 <- 
  tib %>% 
  mutate(date_obs = ymd(date_obs),
         date_end = lag(date_obs),
         date_end = case_when(is.na(date_end)~ ymd("2021-04-13"),
                              TRUE ~ date_end))

ggplot(tib1)+
  geom_segment(aes(x = date_obs, xend = date_end, y = 1, yend = 1, colour = variable), size = 20 ) +
  scale_colour_manual(values = c("A" = "red", "B" = "blue", "C" = "gray50")) +
  theme_classic()+
  theme(legend.position = "bottom",
        axis.line.y = element_blank(),
        axis.text.y = element_blank(),
        axis.ticks.y = element_blank(),
        axis.title.y = element_blank())

An alternative approach might be to use geom_rect which allows you to include the cells for each time period by using the colour argument.


ggplot(tib1)+
  geom_rect(aes(xmin = date_obs, xmax = date_end, ymin = 1, ymax = 1.5, fill = variable), colour = "black" ) +
  scale_fill_manual(values = c("A" = "red", "B" = "blue", "C" = "gray50")) +
  theme_classic()+
  theme(legend.position = "bottom",
        axis.line.y = element_blank(),
        axis.text.y = element_blank(),
        axis.ticks.y = element_blank(),
        axis.title.y = element_blank(),
        aspect.ratio = 1/6)

data

tib <- tribble(
  ~"id",~"date_obs",~"variable",
  "1","2021-01-06","C",
  "2","2020-11-04","C",
  "3","2020-10-27","B",
  "4","2020-07-02","C",
  "5","2019-09-04","B",
  "6","2019-08-07","C",
  "7","2019-05-08","B",
  "8","2019-03-13","B",
  "9","2018-10-12","A",
  "10","2017-12-12","A"
)

Created on 2021-04-13 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