Issue
How can I get the colors of the elements in a pandas bar plot?
Example: I have a bar plot with historic data for a couple of columns. Now I want to plot a horizontal line with the mean value of each column in the same color as the bars.
This question discusses access to colors of matplotlib line plots: How to get color of most recent plotted line in Python's plt
It allowed to me to get the colors of line plots, but not bar plots. I suppose there could be an equivalent to get_lines()
, but I cannot find it.
"""Access bar plot colors."""
import pandas as pd
df = pd.DataFrame(data={'col1': [1, 2], 'col2': [3, 4]})
ax = df.plot()
# This works fine for line plots
for i, col in enumerate(df):
color = ax.get_lines()[i].get_color()
print(color)
ax = df.plot(kind='bar')
# This does not work: "IndexError: list index out of range"
for i, col in enumerate(df):
color = ax.get_lines()[i].get_color()
print(color)
Solution
You could use .patches
:
>>> ax = df.plot(kind='bar')
>>> print(ax.patches)
[<matplotlib.patches.Rectangle object at 0x7f02e2ba3760>, <matplotlib.patches.Rectangle object at 0x7f02e2ba35e0>, <matplotlib.patches.Rectangle object at 0x7f02e2ba3dc0>, <matplotlib.patches.Rectangle object at 0x7f02e2ba35b0>]
>>> for i, col in enumerate(df):
... color = ax.patches[i].get_facecolor()
... print(color)
...
(0.12156862745098039, 0.4666666666666667, 0.7058823529411765, 1.0)
(0.12156862745098039, 0.4666666666666667, 0.7058823529411765, 1.0)
However as you can see enumerating them doesn’t tell you which patch corresponds to which data. Here we’ve grabbed 2 rectangles of the same color. Therefore I would recommend the .get_legend_handles_labels()
function that is used to build legends:
>>> print(ax.get_legend_handles_labels())
([<BarContainer object of 2 artists>, <BarContainer object of 2 artists>], ['col1', 'col2'])
>>> for bars, column in zip(*ax.get_legend_handles_labels()):
... color = bars[0].get_facecolor()
... print(column, color)
...
col1 (0.12156862745098039, 0.4666666666666667, 0.7058823529411765, 1.0)
col2 (1.0, 0.4980392156862745, 0.054901960784313725, 1.0)
Answered By - Cimbali
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.