【问题标题】:Plotly.js modebar, download as png, give png a namePlotly.js 模式栏,下载为 png,为 png 命名
【发布时间】:2017-07-14 13:46:47
【问题描述】:

我的网页上有一个 Plotly,您可以通过单击模式栏中的图片图标将其下载为 png。但是,当我单击它时,它会以名为 new-plot 的 png 格式下载它,我怎样才能给它一个自定义名称?

我当前的代码(var data 只是数据,所以省略了):

var layout = {
    showlegend: true,
    legend: {
        x: 0,
        y: 1
    },
    xaxis: {
        title: 'Date',
        titlefont: {
            family: 'Courier New, monospace',
            size: 18,
            color: '#7f7f7f'
        }
    },
    yaxis: {
        title: 'Sales',
        titlefont: {
            family: 'Courier New, monospace',
            size: 18,
            color: '#7f7f7f'
        }
    }
};

var options = {
    scrollZoom: true,
    showLink: false,
    modeBarButtonsToRemove: ['zoom2d', 'pan', 'pan2d', 'sendDataToCloud', 'hoverClosestCartesian', 'autoScale2d'],
    displaylogo: false,
    displayModeBar: true,
};

Plotly.newPlot('tester', data, layout, options);

【问题讨论】:

    标签: javascript plotly


    【解决方案1】:

    使用Plotly.downloadImage

    https://plot.ly/javascript/plotlyjs-function-reference/#plotlydownloadimage

    将此添加到按钮回调的模式栏设置中:

    Plotly.downloadImage({
        filename: 'customNamedImage',
        format: 'png', //also can use 'jpeg', 'webp', 'svg'
        height: 500,
        width: 500
    });
    

    编辑:

    我运行了一个自定义示例,我认为您会希望在模式栏中自定义 您自己的下载按钮,如下所示:

    Plotly.newPlot(gd, [{
      y: [1, 2, 1],
      line: { shape: 'spline' }
    }], {
      title: 'custom modebar button',
      width: 400,
      height: 700
    }, {
      showTips: false,
      displayModeBar: true,
      modeBarButtons: [[{
        name: 'custom download button',
        icon: Plotly.Icons.camera,
        click: function (gd) {
          Plotly.downloadImage(gd, {
            filename: 'your_custom_name',
            format: 'jpeg',
            width: gd._fullLayout.width,
            height: gd._fullLayout.height
          })
        }
      }, 'toImage'
      ], []]
    })
    

    【讨论】:

    • 我需要在哪里添加?
    • 感谢width: gd._fullLayout.width。这非常有帮助!
    【解决方案2】:

    在新版本的 Plotly (v1.38+) 中有一种更简单的方法可以做到这一点。在配置中使用toImageButtonOptions 参数,如下所示:

    Plotly.newPlot(graphDiv, data, layout, {
        toImageButtonOptions: {
            filename: 'image_filename',
            width: 800,
            height: 600,
            format: 'png'
        }
    });
    

    您可以省略不需要使用默认值的选项。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-09-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-11-06
      • 2015-08-21
      • 1970-01-01
      相关资源
      最近更新 更多