Black Lives Matter. Please consider donating to Black Girls Code today.

Bar plot, sort by value, color by other attribute

Hello everyone, I hope you are well in these special times.

I have a dataframe with two cols, one of which I’m interested in having as the y value, let’s call it vals. The other col, let’s call it cat can only contain two values Y or N, which I want to use as the color of each bar. The issue is I want the bars to be sorted by vals.

I was able to do this by sorting by vals beforehand, creating a list with two values for the colors (same length as the data), and providing plotly with a separate array/list with color for each bar (by providing the marker dictionary with a color array) but now I’m unable to give this chart a proper legend. As I have two colors, I want the legend to have 2 items as well, and not the same number as the length of the data.

How can this be done?

This is what I’m currently getting - this includes the legend and different colors, but the the chart isn’t sorted by Y:

OR: The chart is sorted, the colors are correct, but how do I add a legend for the two different colors?

OK, here’s the closest I got to a solution, which is no sufficient IMO. What I did was create two new dataframes. In one, where cat is (say) “blue”, I’ve deleted all vals with cat that has a value of “red”. In the second, I did the exact opposite.

The result is a chart with two traces, properly marked, but that look weird. Every time there’s a switch from “red” to “blue” there’s a gap on the x-axis, the source of which I’m not sure of. Any insights?

Basically, each data point here is two data points, one from each trace. One is the true value for the trace, and one is just 0. This looks awful in my opinion and if anyone has an idea how to solve it I’d very much appreciate it.

Solved with barmode=stack