我想绘制一些数据,其中我使用自定义转换来实现不同的色阶。如此处所示,标签有时或有时根本没有。我希望标签被舍入并显示颜色代表的值,而不是转换。
我已经能够成功地将其应用于非负面规模,并且我认为它与inverse
中的否定数字或trans_new
来电有关,我不会这样做从文档中可以理解:
以下是我探讨过的一些链接:
R: custom ggplot2 color-transform gives error in labels
GGplot custom scale transformation with custom ticks
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 = "")
答案 0 :(得分:2)
参数inverse
采用的函数是原始变换的数学逆。如果你记录变换,逆是指数。需要反函数来计算与所选中断对应的标签。 (您进行对数转换以获取缩放数据,然后进行逆变换以获取标签。另请参阅this SO post.)
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)
只是为了确保图例以正确的顺序显示。否则它们会以随机顺序出现。