代码之家  ›  专栏  ›  技术社区  ›  Esther

使用ggplot2和viridis,根据其他变量填充柱状图

  •  2
  • Esther  · 技术社区  · 7 年前

    我试图在ggplot中创建这个图中的左上角图形,使用viridis创建颜色渐变。

    这是我的示例数据:

    模拟T值 数据=数据。帧(SIM=1:10000, t_0=rt(n=10000,df=12,ncp=0) t_1=rt(n=10000,df=12,ncp=1.2) #计算p值 数据=数据%gt;% 突变(p_0=2*p t(t_0,df=12,lower.tail=ifelse(t_0>0,false,true)), p_1=2*p t(t_1,df=12,lower.tail=ifelse(t_1>0,false,true))) #从宽到长转换 data.long=数据%gt;% 收集(条件,测量,t_0:p_1)%>% 分离(col=条件,into=c(“para”,“hyp”),sep=“u”) #转换为宽重复度量值格式 data.wide=data.long%>%排列(key=para,测量)

    要在左侧创建图表,我需要根据右侧图表中的相应值为柱状图上色。如果t=0(对应于p接近1),则图表应为黄色;如果t>4(对应于p接近0),则填充应为深蓝色。此帖显示了如何使用scale_fill_gradientn创建类似的图形,但不幸的是,它不适用于我使用cut()创建的离散值。

    这是我最近得到的,但是我希望图的X=0的黄色与边缘的深蓝色相混合。

    基于t值创建容器 t0bins<-序列(-12,12,by=1) #计算相应的p值 pt0bins<-2*pt(t0bins,df=12,lower.tail=false) ggplot(data.wide,aes(x=t,fill=cut(..x.,breaks=get(“t0bins”,envir=globalenv)))+ 几何柱状图(binwidth=0.1)+ 比例填充绿色(离散=t)

    
    

    它给出: .

    以下是我的示例数据:

    # 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)
    

    它给出:

    1 回复  |  直到 7 年前
        1
  •  1
  •   Roman    7 年前

    你可以试试

    库(tidyverse)
    图书馆(Viridis)
    数据范围%gt;%
    突变(bins=切割(t,breaks=t0bins))%>%
    ggplot(,aes(x=t,fill=bin))。+
    几何柱状图(binwidth=0.1)+
    
    

    enter image description here

    推荐文章