对于类似于以下数据框的数据框,我想制作一个网格,其中产品和批次在y轴上,年份在x轴上,并填充单元格(颜色=红色),其中结果> =1。单元格结果<1时应保持白色。 另外,我想在红色单元格(而不是白色单元格)中显示“结果”列中的值。
df <- data.frame(product = c("A","A","A","A","B","B","B","B"),
batch = c(1,2,1,2,1,2,1,2),
year = c(2018,2018,2019,2019,2018,2018,2019,2019),
outcome = c(.52,.13,.63,.27,1.5,.15,.19,2.1))
这是我到目前为止的内容,但是我找不到将产品添加到y轴的方法:
ggplot(df, aes(x = as.factor(year), y = as.factor(batch), fill = outcome >= 1))+
geom_tile(colour = 'black')+
scale_fill_manual(values = c('FALSE' = 'white', 'TRUE' = 'red')) +
theme_bw()
所需的输出:
答案 0 :(得分:1)
您可以创建一个新变量:
library(tidyverse)
df <- data.frame(product = c("A","A","A","A","B","B","B","B"),
batch = c(1,2,1,2,1,2,1,2),
year = c(2018,2018,2019,2019,2018,2018,2019,2019),
outcome = c(.52,.13,.63,.27,1.5,.15,.19,2.1))
df %>%
mutate(pb = paste(product, batch, sep = " / ")) %>%
ggplot( aes(x = as.factor(year), y = fct_rev(pb), fill = outcome >= 1))+
geom_tile(colour = 'black') +
geom_text(aes(label = if_else(outcome >= 1, outcome, NA_real_))) +
scale_fill_manual(values = c('FALSE' = 'white', 'TRUE' = 'red')) +
labs(x = "Year",
y = "Product / batch") +
theme_bw() +
theme(axis.title.y = element_text(angle = 0))