ggplot中自定义渐变颜色渐变的标签

我想绘制一些数据,在这里我使用一种自定义转换来分散色彩比例。 如此处所示,标签有时甚至根本没有。 我希望标签能够圆整,并显示颜色代表的价值而不是转型。

在这里输入图像描述

我已经能够成功地将其应用于非负面的规模,我相信它对trans_new的负数或inverse调用trans_new ,我从文档中不太明白:

以下是我探索的一些链接:

R:自定义ggplot2颜色转换给标签中的错误

GGplot自定义刻度转换与自定义刻度

https://github.com/tidyverse/ggplot2/issues/980看起来对我的头很有帮助

library(scales)
library(tidyverse)

log_both <- function(x){ifelse(x == 0, 0, log(abs(x)) * sign(x))}

log_both_trans <- 
  function(){
    trans_new(name = 'log_both', 
              transform = log_both,
              inverse = log_both) #not clear what `inverse` does
  }

df <-
  tibble(y = (-10:10),
         x = (y^4)*sign(y))

ggplot(df) +
  #no transformation
    geom_point(aes(factor(x), y = 1, fill = x), shape = 21, size = 10) +
    scale_fill_gradient2(low = "blue", mid = "white", high = "red") +
  #transformed
    geom_point(aes(factor(x), y = - 1, color = x), size  = 10) +
    scale_color_gradient2(low = "blue", mid = "white", high = "red", trans = "log_both") +
  ylim(-2, 2) +
  labs(colour = "transformed", fill = "default", x = "", y = "")

参数inverse取一个函数,它是原始变换的数学倒数。 如果你记录变换,则逆是幂。 计算与所选断点相对应的标签需要反算。 (您可以对数据进行日志转换以获取缩放数据,然后进行反转换以获取标签。另请参阅此SO帖子。)

library(scales)
library(tidyverse)

log_both <- function(x){ifelse(x == 0, 0, log(abs(x)) * sign(x))}
exp_both <- function(x){exp(abs(x)) * sign(x)} # this is the inverse of log_both

log_both_trans <- 
  function(){
    trans_new(name = 'log_both', 
              transform = log_both,
              inverse = exp_both)
  }

df <-
  tibble(y = (-10:10),
         x = (y^4)*sign(y))

ggplot(df) +
  #no transformation
  geom_point(aes(factor(x), y = 1, fill = x), shape = 21, size = 10) +
  scale_fill_gradient2(low = "blue", mid = "white", high = "red",
                       guide = guide_colorbar(order = 1)) +
  #transformed
  geom_point(aes(factor(x), y = - 1, color = x), size  = 10) +
  scale_color_gradient2(low = "blue", mid = "white", high = "red",
                        trans = "log_both",
                        breaks = c(-10000, -100, 0, 100, 10000), # desired breaks on transformed scale
                        guide = guide_colorbar(order = 2)) +
  ylim(-2, 2) +
  labs(colour = "transformed", fill = "default", x = "", y = "")

在这里输入图像描述

线条guide = guide_colorbar(order = 1)guide = guide_colorbar(order = 2)仅用于确保图例以正确的顺序显示。 否则它们以随机顺序出现。

链接地址: http://www.djcxy.com/p/30905.html

上一篇: labels for custom diverging color gradient in ggplot

下一篇: like clusters in ggplot with nmds?