简体   繁体   English

如何在 R 中创建带有彩色单元格的水平图?

[英]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.我有以下数据集(测试),并想根据“变量”值创建一个带有不同 colors 的“单元格”的水平条 plot。 For example, "A" in red, "B" in blue, and "C" in gray colors.例如,“A”为红色,“B”为蓝色,“C”为灰色 colors。 The end plot should look like a "colorized stack progress bar".末端 plot 应该看起来像一个“彩色堆栈进度条”。 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.另一种方法可能是使用geom_rect ,它允许您通过使用颜色参数来包含每个时间段的单元格。


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)reprex package (v2.0.0) 于 2021 年 4 月 13 日创建

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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