小值变动无形使用scale_colour_gradient2小值变动无形使用scale_colour

2019-05-12 06:36发布

我想在这地块小的回报更为明显。 最合适的功能似乎scale_colour_gradient2 ,但洗出来的小回报,这最经常发生。 使用limits帮助,但我不能工作,如何设置OOB(出界),所以它只是有一个“饱和”的价值,而不是为灰色。 而数变换只是做小值脱颖而出。 已经有人想出如何优雅地做到这一点?

library(zoo)
library(ggplot2)
library(tseries)

spx <- get.hist.quote(instrument="^gspc", start="2000-01-01",
                      end="2013-12-14", quote="AdjClose",
                      provider="yahoo", origin="1970-01-01",
                      compression="d", retclass="zoo")
spx.rtn <- diff(log(spx$AdjClose)) * 100
rtn.data <- data.frame(x=time(spx.rtn),yend=spx.rtn)

p <- ggplot(rtn.data) +
  geom_segment(aes(x=x,xend=x,y=0,yend=yend,colour=yend)) +
  xlab("") + ylab("S&P 500 Daily Return %") +
  theme(legend.position="null",axis.title.x=element_blank())

# low returns invisible
p + scale_colour_gradient2(low="blue",high="red")
# extreme values are grey
p + scale_colour_gradient2(low="blue",high="red",limits=c(-3,3))

# log transform returns has opposite problem
max_val <- max(log(abs(spx.rtn)))
values <- seq(-max_val, max_val, length = 11)

library(RColorBrewer)
p + scale_colour_gradientn(colours = brewer_pal(type="div",pal="RdBu")(11),
                           values = values
                           , rescaler = function(x, ...) sign(x)*log(abs(x)), oob = identity)

Answer 1:

这是另一种可能性,使用scale_colour_gradientn 。 的映射colours是使用设置values = rescale(...)使得分辨率为接近零的值更高。 我有看一些颜色尺度在这里: http://colorbrewer2.org 。 我通过接近白色选择了5级发散的配色方案,RdBu,从红色到蓝色。 有可能是更好地满足您的需要其他尺度,这只是显示的基本原则。

# check the colours
library(RColorBrewer)
# cols <- brewer_pal(pal = "RdBu")(5) # not valid in 1.1-2
cols <- brewer.pal(n = 5, name = "RdBu") 
cols
# [1] "#CA0020" "#F4A582" "#F7F7F7" "#92C5DE" "#0571B0"
# show_col(cols) # not valid in 1.1-2
display.brewer.pal(n = 5, name = "RdBu")

使用rescale ,-10对应于蓝#0571B0; -1 =淡蓝色#92C5DE; 0 =淡灰色#F7F7F7; 1 =淡红色#F4A582; 10 =红色#CA0020。 -1和1之间的值之间的光的蓝色和红色光,等Ç插值。 因此,映射是不是线性的,分辨率为小的值更高。

library(ggplot2)
library(scales) # needed for rescale
ggplot(rtn.data) +
  geom_segment(aes(x = x, xend = x, y = 0, yend = yend, colour = yend)) +
  xlab("") + ylab("S&P 500 Daily Return %") +
  scale_colour_gradientn(colours = cols, 
                         values = rescale(c(-10, -1, 0, 1, 10)),
                         guide = "colorbar", limits=c(-10, 10)) +
  theme(legend.position = "null", axis.title.x = element_blank())



Answer 2:

怎么样:

p + scale_colour_gradient2(low="blue",high="red",mid="purple")

要么

p + scale_colour_gradient2(low="blue",high="red",mid="darkgrey")


文章来源: Small value variation invisible using scale_colour_gradient2
标签: r colors ggplot2