plotly : I want to include some pattern in the bars of a bar chart

Viewed 2210

Language : JavaScript

I want to include some patterns in my bars of bar chart. I dont see anything available in plotly by default to serve the purpose .

So I tried getting hold of the "point" element in the dynamically generated "svg" component.And then create a "pattern" element. I thought after creating the inner pattern tag , i will able to set cusotom attributes.

But its not working at all.

Below is the code sample used :

var data = [{
  x: ['giraffes', 'orangutans', 'monkeys'],
  y: [20, 14, 23],
  type: 'bar'
}];

Plotly.newPlot('myDiv',data);

var ticks = document.getElementsByClassName('point');
for (var i = 0; i < ticks.length; i += 1) {
          var patt = document.createElement("pattern");
          patt.setAttribute('patternTransform','rotate(30)');
          patt.setAttribute('patternUnits','userSpaceOnUse');
          patt.setAttribute('fill', 'red');
          ticks[i].appendChild(patt);

}

And I am taking reference of the below "" tag which I found online somewhere..

<pattern id="diagonal-stripes-4-8" x="0" y="0" width="8" height="8"    patternUnits="userSpaceOnUse" patternTransform="rotate(30)">
<rect x="0" y="0" width="4" height="8" style="stroke:none; fill:purple;" />
</pattern>
1 Answers

There now is builtin pattern support. We can now use a pattern object.

The pattern has multiple options, one of them being shape:

Type: enumerated or array of enumerateds , one of ( "" | "/" | "" | "x" | "-" | "|" | "+" | "." )
Default: ""
Sets the shape of the pattern fill. By default, no pattern is used for filling the area.

So for example you could do something like this:

const data = [{
  x: ["giraffes", "orangutans", "monkeys"],
  y: [20, 14, 23],
  type: "bar",
  marker: {
    pattern: {
      shape: "-",
    },
  },
}, ];

Plotly.newPlot("graph", data);
<script src="https://cdn.plot.ly/plotly-2.3.1.min.js"></script>

<div id="graph" style="width: 1000; height: 550px"></div>

For some examples of pattern combinations you could look at this.

Now in the case your specific pattern is not covered by the options pattern provides, you could target the pattern element and set your own custom pattern. As an example I will take the rectangle pattern example you listed in your question:

const data = [{
  x: ["giraffes", "orangutans", "monkeys"],
  y: [20, 14, 23],
  type: "bar",
  marker: {
    pattern: {
      shape: "-",
    },
  },
}, ];

Plotly.newPlot("graph", data);

document.querySelector("pattern").innerHTML = "<rect x='0' y='0' width='4' height='8' style='stroke:none; fill:purple;' />"
<script src="https://cdn.plot.ly/plotly-2.3.1.min.js"></script>

<div id="graph" style="width: 1000; height: 550px"></div>

Related