使用ggplot2和viridis,根据其他变量填充直方图

Using ggplot2 and viridis, fill histogram based on other variable

我正在尝试在 ggplot 中创建此图中左上角的图形,使用 viridis 制作颜色渐变。

这是我的示例数据:

# simulate t-values
data = data.frame(sim =1:10000,
                  t_0= rt(n = 10000,df =12, ncp=0), 
                  t_1 = rt(n = 10000,df =12, ncp=1.2))
# compute p-values
data = data %>% 
  mutate(p_0 = 2* pt(t_0, df=12, lower.tail = ifelse(t_0 > 0,FALSE ,TRUE)),
         p_1 = 2* pt(t_1, df=12, lower.tail = ifelse(t_1 > 0,FALSE ,TRUE)))

# convert from wide to long
data.long = data %>% 
  gather(condition,measurement, t_0:p_1) %>%
  separate(col=condition, into=c("para","hyp"), sep = "_")

# convert to wide repeated measures format
data.wide = data.long %>% spread(key = para, measurement)

要创建左侧的图表,我需要根据右侧图表中的相应值为直方图着色。如果t=0(对应p接近1),图形应该是黄色,如果t>4(对应p接近0),填充应该是深蓝色。 展示了如何使用 scale_fill_gradientn 创建类似的图形,不幸的是,它不适用于我使用 cut() 创建的离散值。

这是我最接近的结果,但是我希望图形在 x=0 处具有黄色并在边缘处混合为深蓝色。

# create bins based on t-values
t0bins <- seq(-12, 12, by = 1)
# compute corresponding p-values
pt0bins <- 2*pt(t0bins, df = 12, lower.tail = FALSE)



 ggplot(data.wide, aes(x=t, fill=cut(..x.., breaks=get("t0bins", envir=.GlobalEnv)))) +
  geom_histogram(binwidth=0.1)+
  scale_fill_viridis(discrete=T)

给出:

你可以试试

library(tidyverse)
library(viridis)
data.wide %>% 
  mutate(bins=cut(t, breaks=t0bins)) %>% 
{ggplot(.,aes(x=t, fill=bins)) +
  geom_histogram(binwidth=0.1)+
  scale_x_continuous(limits =c(-12,12)) +
  scale_fill_manual(drop=FALSE,values = c(viridis(nlevels(.$bins)/2), viridis(nlevels(.$bins)/2, direction = -1)))}