我正在尝试在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),则填充应为深蓝色。 This post显示了如何使用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)
答案 0 :(得分:1)
你可以尝试
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)))}