I have the following code:
from pandas import DataFrame
import matplotlib.pyplot as plt
if __name__ == '__main__':
lower_bound = [0, 1, 2, 3]
value = [1, 2, 3, 4]
upper_bound = [2, 3, 4, 5]
d = {'Lower bound': lower_bound, 'Value': value, 'Upper bound': upper_bound}
df = DataFrame(data=d)
ax = df.plot()
plt.show()
It creates the following plot:

I want the same plot, but, in the legend, I want the "Lower bound" and "Upper bound" combined into one, say, "Bounds". And, of course, the two bounds will now be the same color (whatever color is given on the legend for "Bounds").
Seems like this did the trick:
from pandas import DataFrame
import matplotlib.pyplot as plt
if __name__ == '__main__':
lower_bound = [0, 1, 2, 3]
value = [1, 2, 3, 4]
upper_bound = [2, 3, 4, 5]
d = {'Lower bound': lower_bound, 'Value': value, 'Upper bound': upper_bound}
df = DataFrame(data=d)
ax = df.plot(color=["Blue", "Blue", "Red"])
lines, labels = ax.get_legend_handles_labels()
ax.legend([lines[0], lines[2]], ["Bounds", "Value"])
plt.show()
My guess as to why the colors are in that order: pandas must sort column names before it plots. You'd think it would be
colors = ["Blue", "Red", "Blue"]
But note that "Lower Bound", "Upper Bound", and "Value" is the alphabetical order of your keys.
NOTE: This was anaconda 2.7, behavior may be different for Python 3.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With