首页 > 解决方案 > pandas barplot 为每个变量选择颜色

问题描述

我通常使用 matplotlib,但在玩熊猫绘图时遇到了意想不到的行为。我假设以下将返回红色和绿色边缘而不是交替。我在这里想念什么?

import pandas as pd
import matplotlib.pyplot as plt
df = pd.DataFrame({"col1":[1,2,4,5,6], "col2":[4,5,1,2,3]})

def amounts(df):
    fig, ax = plt.subplots(1,1, figsize=(3,4))
    (df.filter(['col1','col2'])
       .plot.bar(ax=ax,stacked=True, edgecolor=["red","green"],
                 fill=False,linewidth=2,rot=0))
    ax.set_xlabel("")
    plt.tight_layout()
    plt.show()

amounts(df)

标签: pythonpandas

解决方案


我认为分别绘制每一列并将bottom参数设置为堆叠条形可提供您想要的输出。

import pandas as pd
import matplotlib.pyplot as plt
df = pd.DataFrame({"col1":[1,2,4,5,6], "col2":[4,5,1,2,3]})

def amounts(df):
    fig, ax = plt.subplots(1,1, figsize=(3,4))
    
    df['col1'].plot.bar(ax=ax, linewidth=2, edgecolor='green', rot=0, fill=False)
    df['col2'].plot.bar(ax=ax, bottom=df['col1'], linewidth=2, edgecolor='red', rot=0, fill=False)

    plt.legend()
    plt.tight_layout()
    plt.show()
    
amounts(df)

在此处输入图像描述


推荐阅读