如何将Plotly r中的色标转换为对数标尺

时间:2019-11-29 03:48:17

标签: r plotly

我正在尝试为R中的色条设置对数标度,关于如何做到这一点的任何想法?

我的代码:

TEST_DATAFRAME = read.table(TEST_FILE, sep="\t",skip=2, header=T)
PROD_DATAFRAME = read.table(PROD_FILE, sep="\t",skip=2, header=T)

PARAMETER = "Vf_High"
LST_RESIDUAL <- PROD_DATAFRAME[PARAMETER] - TEST_DATAFRAME[PARAMETER]
PARAM_DATAFRAME <- data.frame("NEW_MEASUREMENT" = TEST_DATAFRAME[PARAMETER], 
                              "OLD_MEASUREMENT" = PROD_DATAFRAME[PARAMETER], 
                              "RESIDUAL" = LST_RESIDUAL)

colnames(PARAM_DATAFRAME) <- c("NEW_MEASUREMENT","OLD_MEASUREMENT","RESIDUAL")

p <- plot_ly(PARAM_DATAFRAME, x = ~OLD_MEASUREMENT, y = ~NEW_MEASUREMENT, color=~RESIDUAL,  colorscale = "Log",
             hovertext = paste("<b>New Measurement :</b>", PARAM_DATAFRAME$NEW_MEASUREMENT,
                               "<br><b>Old Measurement :</b>", PARAM_DATAFRAME$OLD_MEASUREMENT,
                               "<br><b>Residual :</b>" , PARAM_DATAFRAME$RESIDUAL)) %>% add_markers()

#p <- layout(p, color = list(type = "log"))
p

这是我当前的输出:

enter image description here

我还尝试了以下代码:

TEST_DATAFRAME = read.table(TEST_FILE, sep="\t",skip=2, header=T)
PROD_DATAFRAME = read.table(PROD_FILE, sep="\t",skip=2, header=T)

PARAMETER = "Vf_High"
LST_RESIDUAL <- PROD_DATAFRAME[PARAMETER] - TEST_DATAFRAME[PARAMETER]
PARAM_DATAFRAME <- data.frame("NEW_MEASUREMENT" = TEST_DATAFRAME[PARAMETER], 
                              "OLD_MEASUREMENT" = PROD_DATAFRAME[PARAMETER], 
                              "RESIDUAL" = abs(LST_RESIDUAL))

colnames(PARAM_DATAFRAME) <- c("NEW_MEASUREMENT","OLD_MEASUREMENT","RESIDUAL")

brks <- pretty(range(PARAM_DATAFRAME$RESIDUAL))
gg <- ggplot(PARAM_DATAFRAME, aes(NEW_MEASUREMENT, OLD_MEASUREMENT, color = RESIDUAL)) +
  geom_point() +
  scale_colour_gradient(
    low = "blue", high = "red",
    trans = "log", breaks = brks, labels = brks) +
  theme_minimal()

ggplotly(gg)

这是结果:

enter image description here

如何给它加上清晰的标签? 我想将颜色栏配置如下:

enter image description here

1 个答案:

答案 0 :(得分:1)

您可以使用ggplot生成对数色标,然后让plotly::ggplotlyggplot grob变成一个可绘制的对象。

由于您没有提供可重复的示例数据,因此以下示例基于mtcars

brks <- pretty(range(mtcars$disp))
gg <- ggplot(mtcars, aes(mpg, wt, colour = disp)) +
    geom_point() +
    scale_colour_gradient(
        low = "blue", high = "red",
        trans = "log", breaks = brks, labels = brks) +
    theme_minimal()

ggplotly(gg)

enter image description here


更新

为回应您的评论,这是一个最小的可重复示例。

首先我们生成一些样本数据

set.seed(2018)
df <- data.frame(
    x = 1:100,
    y = 1:100 + rnorm(100),
    val = 10^seq(-5, 2, length.out = 100))

然后我们定义合适的休息时间

brks <- 10^seq(floor(log10(min(df$val))), ceiling(log10(max(df$val))), by = 1)

生成ggplot grob

gg <- ggplot(df, aes(x, y, colour = val)) +
    geom_point() +
    scale_colour_gradient(
        low = "blue", high = "red",
        trans = "log",
        breaks = brks,
        labels = brks) +
    theme_minimal()

最后显示为plotly个对象

ggplotly(gg)

enter image description here