【发布时间】:2021-11-10 09:22:21
【问题描述】:
如何获取 pandas 条形图中元素的颜色?
示例:我有一个包含几列历史数据的条形图。现在我想用与条形相同颜色的每列的平均值绘制一条水平线。
这个问题讨论了对 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)
【问题讨论】:
-
这个问题及其答案可能会有所帮助:stackoverflow.com/q/22688915/11946287
标签: python pandas matplotlib