使用viridis和Map值在直方图中绘制颜色 [英] Use viridis and Map values to colour in a histogram plot

查看:438
本文介绍了使用viridis和Map值在直方图中绘制颜色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在左侧重新创建两个图: 假定颜色渐变在0时较亮,而在极值处则较暗.我想使用viridis包创建颜色渐变.

I am trying to recreate the two plots on the left: The colour gradient is supposed to be lighter at 0, and darker at the extreme values. I want to use the viridis package to create the colour gradient.

这是我的样本数据集:

library(tidyverse)
library(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)

这是我尝试的方法,但是此处的颜色以x轴上的平均值为中心,而不是以0为中心.我不知道该如何正确设置,我认为这是关于尝试在直方图中使用scale_fill.

Here is what I tried, however the colour here is centered around the mean of the values on the x-axis instead of being centered on 0. I can't figure out how to make it right, I think it's something about trying to use scale_fill with the histogram.

ggplot(data.wide) + 
  geom_histogram(aes(x=t,fill=..x..),
                 binwidth=.01 )+
  scale_fill_gradientn(colours = c(viridis::viridis(5),
                                   rev(viridis::viridis(5))[2:5]))+
  facet_wrap(~ hyp  ,ncol=1)

哪个给我这个输出:

推荐答案

对于scale_fill_gradientn,有一个重新缩放功能,可以将观察到的值映射到[0,1],以便进行着色.您可以创建自己的重新缩放器,以将某个数字放在中间.例如

With scale_fill_gradientn, there is a rescaler function that maps your observed values to [0,1] in order to do the coloring. You can create your own rescaler to place a certain number in the middle. For example

center_around <- function(center=0) {
  function(x, to=NA, from=NA) {
    r <- max(abs(from-center))
    (x - (center-r)) / 2/r
  }
}

将返回一个函数,该函数将值以给定数字为中心,然后重新缩放为0、1.您可以将其与

will return a function that will center values around a given number then rescale to 0, 1. You can use it with

ggplot(data.wide) + 
  geom_histogram(aes(x=t,fill=..x..),
                 binwidth=.01 )+
  scale_fill_gradientn(colours = c(viridis::viridis(5),
                                   rev(viridis::viridis(5))[2:5]),
                       rescaler = center_around(0))+
  facet_wrap(~ hyp  ,ncol=1)

获得

这篇关于使用viridis和Map值在直方图中绘制颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆