【问题标题】:Formatting text from axis ticks in plotly using tickformat使用刻度格式从轴刻度中格式化文本
【发布时间】:2017-09-20 04:16:44
【问题描述】:

是否可以使用 tickformat 向 xaxis 和 yaxis 刻度添加格式?

想法是将轴的长名称切割为:

axiswithaverylongname --> axisw...

在 plotly api 参考中有格式化日期的示例 https://plot.ly/javascript/reference/#layout-xaxis-tickformat

他们还参考了 d3 文档 https://github.com/d3/d3-format/blob/master/README.md

来自情节参考:

tickformat (string) 
default: "" 
Sets the tick label formatting rule using d3 formatting mini-languages 
which are very similar to those in Python. For numbers, see: 
https://github.com/d3/d3-format/blob/master/README.md#locale_format 
And for dates see: https://github.com/d3/d3-time-
format/blob/master/README.md#locale_format We add one item to d3's 
date formatter: "%{n}f" for fractional seconds with n digits. For 
example, "2016-10-13 09:15:23.456" with tickformat "%H~%M~%S.%2f" 
would display "09~15~23.46"

【问题讨论】:

    标签: javascript d3.js plotly


    【解决方案1】:

    据我所知,没有办法直接通过tickformat 进行操作,但几行 JavaScript 代码将为您解决问题。

    Plotly.d3.selectAll(".xtick text").each(function(d, i) {
      Plotly.d3.select(this).html(Plotly.d3.select(this).html().substr(0, 5));
    });
    

    使用 d3 的 seleectAllwet 获取 x 轴上的所有 text 标签,并使用初始标签的前 5 个字母更新文本。

    您可以自动执行此操作,也可以在下面的示例中按下按钮时执行此操作。

    var trace1 = {
      x: ["A", "B1", "axiswithaverylongname", "Wow, wait a second, that's way tooooo long"],
      y: [1, 2, 3, 4],
      type: "bar"
    };
    
    var myPlot = document.getElementById('myPlot')
    Plotly.newPlot('myPlot', [trace1]);
    document.getElementById("cleanButton").addEventListener("click", function(){
      Plotly.d3.selectAll(".xtick text").each(function(d, i) {
        if (Plotly.d3.select(this).html().length > 8) {
          Plotly.d3.select(this).html(Plotly.d3.select(this).html().substr(0, 5) + '...');
        }
      });
    });
    <script src="https://cdn.plot.ly/plotly-latest.min.js"></script>
    <div id="myPlot" style="width:100%;height:100%"></div>
    <button id="cleanButton">Clean x-axis</button>

    【讨论】:

    • @alfaz jikani:我会在我可以访问具有 IE11 的计算机时对其进行测试。
    • @MaximilianPeters,我找到了适用于 IE11 的解决方案。参考:stackoverflow.com/a/38285239/5492926Plotly.d3.selectAll(".xtick text, .ytick text").each(function (d, i) { // Using jquery // Use d.text instead of reading DOM by "Plotly.d3.select(this).html()" $(this).text(d.text.substr(0, 5)); });
    猜你喜欢
    • 2017-03-16
    • 2017-08-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多