python - Pandas 情节 : fixing a color by value

标签 python pandas

有一个 df:

import random
import pandas as pd
def get_row():
    row = {"date" : random.choice(range(10)), "status" : random.choice(["won", "lost", "onoing"]), "id" : random.choice(range(10))}
    return row
df = pd.DataFrame([get_row() for i in range(100)])
tab  = df.pivot_table(index="date", columns="status", values="id", aggfunc="count")
tab

这给了我: enter image description here

我可以尝试绘制:

tab.plot.bar(stacked=True)

enter image description here

如何固定每列的颜色? 我希望“失败”为红色,“获胜”为绿色,“正在进行”为蓝色。

好吧,我找到了答案:

gcolors = {'lost': 'red', 'onoing': 'blue', 'won': 'green'}
tab.plot.bar(stacked=True, color=[gcolors[group] for group in tab])

给出: enter image description here

最佳答案

嗯,正如我所说,在提出问题时,我找到了答案:

gcolors = {'lost': 'red', 'onoing': 'blue', 'won': 'green'}
tab.plot.bar(stacked=True, color=[gcolors[group] for group in tab])

关于python - Pandas 情节 : fixing a color by value,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51333793/

相关文章:

python - 使用 Python-Xarray 重新网格化坐标

Python 正则表达式 : Can't extract message containing escaped quotes

python - 存在缺失值时对所有可能的组进行自定义分组

python - pd.read_csv 的小数问题

python - 如何根据 Pandas 数据框中的前几行添加带有值的额外列?

python - 如何在 Python 中过滤 ttk.treeview?

python - 如何使用 Python 和 Pandas 在时间翻转时添加 24 小时

python - 获取前一个较小值的索引

pandas - pandas 使用哪种方法计算百分位数?

python - 如何在 tkinter 标签中将文本居中,如 Microsoft Word 居中打字模式