将主要刻度标签设置为在 R 中的 Plotly 图中显示为科学记数法刻度、设置为、图中、标签

由网友(赖人寻味i)分享简介:我试图让 plotly 以科学记数法表示值,而不管它们的大小,即 100 应该是刻度中的 1E02,但它一直显示低于 10.000 的数字作为正常注释.I'm trying to get plotly to put values in scientific notation regardless of their s...

我试图让 plotly 以科学记数法表示值,而不管它们的大小,即 100 应该是刻度中的 1E02,但它一直显示低于 10.000 的数字作为正常注释.

I'm trying to get plotly to put values in scientific notation regardless of their size, i.e. 100 should be 1E02 in the ticks, but it keeps showing numbers below 10.000 as normal annotation.

设置格式是通过exponentformat = "E""但它只影响较大的数字.

Setting the format is done through exponentformat = "E""but it only affects larger numbers.

这是我如何编写它的示例代码:

Here is an example code of how I write it:

f2 <- list(family = "Old Standard TT, serif", size = 14, color = "black")

ax <- list(showticklabels = TRUE, tickfont = f2,  showgrid=F,  zeroline=T,  showline=T,  nticks = 4,  exponentformat = "E")
ay <- list(nticks = 4,  showticklabels = TRUE,  tickfont = f2,  showgrid=F,  zeroline=T,  showline=T,  range =c(0,max(mtcars$disp*1.2)),  exponentformat = "E")

plot_ly(x = mtcars$mpg  , y = mtcars$disp) %>%
  add_trace(type = 'scatter', mode = 'markers', 
            marker = list(color = c('black'))) %>%
  add_lines(hoverinfo='none', line = list(color = 'black')) %>%
  layout(title = 'A plot in science',yaxis = ay, xaxis = ax,
         showlegend = FALSE, hovermode = "y")

将值控制在 10k 以上的范围内会得到所需的输出:

manipulating the values to be in the 10k plus range gives the desired output though:

 mtcars$disp <- mtcars$disp *100 

推荐答案

如果 Plotly 没有提供所需的功能,我们就自己用 JavaScript 做吧.

Let's just do it ourselves in JavaScript, if Plotly doesn't provide the needed functionality.

让我们使用 d3 抓取 y 轴上的所有刻度

let's grab all ticks on the y-axis using d3

ticks = Plotly.d3.selectAll('g.ytick');

用R语言让你的图动起来

原始数据存储在data.x

然后将每一个的表示改为科学记数法

then change the representation of each one to scientific notation

Plotly.d3
      .selectAll('g.ytick')
      .each(function(data, i) 
        {
           Plotly.d3.select(this)
                    .select('text')
                    .html(formatNumber(data.x, 2));
        }) 

最后在我们的图中使用 htmlwidgets 注入所有代码

p <- onRender(p, javascript)

p <- onRender(p, javascript)

现在它只是一次更改,每次用户缩放或修改绘图时,更改都会丢失.为了确保每次将代码包装在函数 fix_ticks() 中并添加到 Plotly 的 plotly_afterplot 事件(elhtmlwidget 元素)

now it would be one-time only change, every time a user zooms or modifies the plot the changes would be lost. In order to make sure that changes are applied every time the code is wrapped in a function fix_ticks() and added to Plotly's plotly_afterplot event (el is the htmlwidget element)

el.on('plotly_afterplot', fix_ticks);

更新

如果你想改变科学记数法的格式,你可以写你的函数,例如

If you want to change the format of the scientific notation, you could write your function, e.g.

function formatNumber(num, desiredLength)
{
  num = num.toExponential().toUpperCase();
  var r = /(d*)([E][-+])(d*)/;
  var fields = r.exec(num);
  if (fields !== null && fields.length > 3)
  {
    return fields[1] + fields[2] + fields[3].padStart(desiredLength, '0');
  }
  else
  {
    return num;
  }   
}

然后为每个刻度调用它

ticks.forEach(function(tick) 
{
  var num = parseInt(tick[0].innerHTML); 
  tick[0].innerHTML = formatNumber(num, 2);
})

注意:这可能在 RStudio 中不起作用,但在保存输出后会在浏览器中正确显示.

Note: this might not work in RStudio but shows up correctly in your browser after saving the output.

完整代码

library(plotly)
library(htmlwidgets)

p <- plot_ly(x = mtcars$mpg  , y = mtcars$disp) %>%
  add_lines()

javascript <- "
function(el, x) 
{
  function fixTicks()
  {

    Plotly.d3
          .selectAll('g.ytick')
          .each(function(data, i) 
            {
               Plotly.d3.select(this)
                        .select('text')
                        .html(formatNumber(data.x, 2));
            }) 
  }

  function formatNumber(num, desiredLength)
  {
    num = num.toExponential().toUpperCase();
    var r = /(d*)([E][-+])(d*)/;
    var fields = r.exec(num);
    if (fields !== null && fields.length > 3)
    {
      return fields[1] + fields[2] + fields[3].padStart(desiredLength, '0');
    }
    else
    {
      return num;
    }
  }

  el.on('plotly_afterplot', fixTicks);
}"

p <- onRender(p, javascript)  
p
阅读全文

相关推荐

最新文章