How to have pattern on the negative values and its own color?

This is my chart:

When I used pattern its own color fade away I only could change the stroke.
these are my data and code:

stack_bar_chart=[{primary_reason: "WAC Adjustment", mean_new_percent_change: 129.17999999999998, year: "2017"}
,{primary_reason: "Survey Rate", mean_new_percent_change: -42.34, year: "2017"}
,{primary_reason: "Help Desk", mean_new_percent_change: 17.29, year: "2017"}
,{primary_reason: "WAC Adjustment", mean_new_percent_change: 123.32999999999997, year: "2018"}
,{primary_reason: "Survey Rate", mean_new_percent_change: 39.87, year: "2018"}
,{primary_reason: "Help Desk", mean_new_percent_change: 237.62999999999997, year: "2018"}
,{primary_reason: "WAC Adjustment", mean_new_percent_change: 63.16, year: "2019"}
,{primary_reason: "Survey Rate", mean_new_percent_change: -31.15000000000001, year: "2019"}
,{primary_reason: "Help Desk", mean_new_percent_change: 8.98, year: "2019"}
,{primary_reason: "WAC Adjustment", mean_new_percent_change: 59.76, year: "2020"}
,{primary_reason: "Survey Rate", mean_new_percent_change: -15.310000000000008, year: "2020"}
,{primary_reason: "Help Desk", mean_new_percent_change: 6.04, year: "2020"}
,{primary_reason: "WAC Adjustment", mean_new_percent_change: 57.99999999999999, year: "2021"}
,{primary_reason: "Survey Rate", mean_new_percent_change: -26.83000000000001, year: "2021"}
,{primary_reason: "WAC Adjustment", mean_new_percent_change: 65.99999999999999, year: "2022"}
,{primary_reason: "Survey Rate", mean_new_percent_change: -69.15000000000002, year: "2022"}
]
new1=Plot.plot({
  color:{legend:true},
  y: {
    grid:true,
    tickFormat: "s"
  },
  marks: [
    Plot.frame({ stroke: "lightgray" }),
    Plot.barY(stack_bar_chart, {x: "year", y: "mean_new_percent_change", fill: "primary_reason",title: d=> `${d.primary_reason}\n${d.mean_new_percent_change}`}),
    Plot.ruleY([0])
  ]
})
{
  const divs = d3.select(new1).selectAll('span');
  const rectangles2 = d3.select(new1).selectAll('rect');
  const svg = d3.select(new1).selectAll('svg');

  /////////////////////////////////////   to add patterns for values<0
  svg
  .append('defs')
  .append('pattern')
    .attr('id', 'diagonalHatch')
    .attr('patternUnits', 'userSpaceOnUse')
    .attr('width', 4)
    .attr('height', 4)
  .append('path')
    .attr('d', 'M3,5 l2,-2')
    .attr('stroke', '#000000')
    .attr('stroke-width', 2);

  rectangles2.filter(function() {
    if (d3.select(this).text().split("\n")[1]<0)
    {
      this.setAttribute("stroke",this.getAttribute("fill"));
      this.setAttribute("fill",'url(#diagonalHatch)');
    }
    return d3.select(this).text().split("\n")[1]<0}
                    )
    .attr("opacity", 1)

}
1 Like

Unfortunately SVG patterns don’t adopt the color of their parent; here’s a function that adds a different pattern for each color:
https://observablehq.com/@recifs/hatched-negatives--support

1 Like

Thank you so much!