Asked  7 Days ago    Answers:  5   Viewed   13 times

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

 Answers

6

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'
  ], []]
})
Saturday, May 14, 2022
 
rici
 
4

Plotly uses the same colors as in d3's scale.category10() function. After 10 colors the whole color scheme starts again from 0.

The colors codes can be found in KDD's answer. The snippet below gives the d3 colors and takes the Plotly colors dynamically from a plot, i.e. even if the Plotly changes the color codes will be correct.

var d3colors = Plotly.d3.scale.category10();
var color_div = document.getElementById('colors');
var data = [];

for (var i = 0; i < 11; i += 1) {
  data.push({
x: [i],
y: [i + 1],
name: i + ": Color: " + d3colors(i),
type: 'bar'
  });
}
Plotly.plot('colors', data);

var node;
var textnode;
for (var i = 0; i < 10; i += 1) {
  var color = d3colors(i);
  node = document.createElement("div");
  node.style.color = color;
  var text = "D3: " + color;
  textnode = document.createTextNode(text);
  node.appendChild(textnode);
  node.appendChild(document.createElement("br"));
  var rgb = Plotly.d3.selectAll('.point').selectAll('path')[i][0].style.fill;
  color = Plotly.d3.rgb(rgb).toString()
  var text = "Plotly: " + color + " ; " + rgb;
  textnode = document.createTextNode(text);
  node.appendChild(textnode);
  color_div.appendChild(node); 
}
<script src="https://cdn.plot.ly/plotly-latest.min.js"></script>
<div id="colors"></div>
Wednesday, July 28, 2021
 
inieto
 
5

You could call HTMLCanvasElement.toDataURL() to get the canvas as PNG base64 string. Here is a working example:

import base64
from selenium import webdriver

driver = webdriver.Chrome()
driver.get("http://curran.github.io/HTML5Examples/canvas/smileyFace.html")

canvas = driver.find_element_by_css_selector("#canvas")

# get the canvas as a PNG base64 string
canvas_base64 = driver.execute_script("return arguments[0].toDataURL('image/png').substring(21);", canvas)

# decode
canvas_png = base64.b64decode(canvas_base64)

# save to a file
with open(r"canvas.png", 'wb') as f:
    f.write(canvas_png)
Thursday, July 29, 2021
 
4

Because it uses external functions, this is sort of a hack, but it does seem to work on any browser. I'm using the tool FileSaver.js to do the file download work, and canvas-toBlob.js to perform the toBlob functioning on Chrome and other browsers.

<script src="https://rawgit.com/eligrey/FileSaver.js/master/FileSaver.js"></script>
<script src ="https://rawgit.com/eligrey/canvas-toBlob.js/master/canvas-toBlob.js"></script>

<h1 onclick="download_image()">Click Here to download image</h1>
<canvas id="myCanvas" width="200" height="100" style="border:1px solid #000000;">

<script>
  // lets put something on a canvas.. 
  // reminder this works without jQuery .ready() only because this script is the last element in the document.
    var c = document.getElementById("myCanvas");
    var ctx = c.getContext("2d");
    ctx.fillStyle = "#FF0000";
    ctx.fillRect(0,0,150,75);
    ctx.moveTo(0,0);
    ctx.lineTo(200,100);
    ctx.stroke();
    ctx.beginPath();
    ctx.arc(95,50,40,0,2*Math.PI);
    ctx.stroke();

    function download_image(){
        // Dump the canvas contents to a file.
        var canvas = document.getElementById("myCanvas");
        canvas.toBlob(function(blob) {
            saveAs(blob, "output.png");
        }, "image/png");
    };
</script>
Monday, August 30, 2021
 
mozlima
 
5

Try using Plotly.update():

function rand() {
return Math.floor(Math.random() * (250 - 0) ) + 0;
}

var data = [
        {
            domain: { x: [0, 1], y: [0, 1] },
            value: 0,
            title: { text: "Speed" },
            type: "indicator",
            mode: "gauge+number"
        }
    ];

var layout = { width: 600, height: 500, margin: { t: 0, b: 0 } };
Plotly.newPlot('myDiv', data, layout);

var cnt = 0;
var interval = setInterval(function() {
Plotly.update('myDiv', {value: rand()}, {}, [0])
if(++cnt === 100) clearInterval(interval);
}, 800);
<head>
	<!-- Load plotly.js into the DOM -->
	<script src='https://cdn.plot.ly/plotly-latest.min.js'></script>
</head>

<body>
	<div id='myDiv'><!-- Plotly chart will be drawn inside this DIV --></div>
</body>
Thursday, December 2, 2021
 
Ergwun
 
Only authorized users can answer the question. Please sign in first, or register a free account.
Not the answer you're looking for? Browse other questions tagged :