Plotly.js modebar, download as png, give png a name

安稳与你 提交于 2020-02-05 03:23:17

问题


I have a Plotly on my webpage and you can download it as a png by clicking the picture icon in the modebar. However when I click it, it downloads it as a png with the name new-plot, how can I give it a custom name?

My current code (var data is just data, so left it out) :

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);

回答1:


Use Plotly.downloadImage

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

Add this to your modebar setup for the button callback:

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

Edit:

I ran a custom example and I think you will want to custimze your own download button in the modebar, like so:

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'
  ], []]
})



回答2:


There's an easier way to do this in newer versions of Plotly (v1.38+). Use the toImageButtonOptions parameter in the config like this:

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

You can leave out options you don't need to use the defaults.



来源:https://stackoverflow.com/questions/45104632/plotly-js-modebar-download-as-png-give-png-a-name

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!