如何获取熊猫条形图中元素的颜色?
示例:我有一个条形图,其中包含几列的历史数据。现在我想绘制一条水平线,每列的平均值与条形颜色相同。
这个问题讨论了对 matplotlib 线图颜色的访问:How to get color of most recent plotted line in Python's plt
它允许我获得线图的颜色,但不能获得条形图的颜色。我想可能有一个等价于get_lines(),但我找不到它。
"""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)
