首页 > 解决方案 > Change the colors of outline and median lines of boxplot in matplotlib

问题描述

I am trying to create boxplot from pandas dataframe using matplotlib.

I am able to get the boxplot and change the linewidth of outlines and median lines, but I would like to change all the colors to black. I tried several ways as described in Pandas boxplot: set color and properties for box, median, mean and Change the facecolor of boxplot in pandas.

However, none of them worked for my case.

Could someone solve these problems?

Here are my codes:

version: python 3.6.5

    import pandas as pd
    from pandas import DataFrame, Series
    import matplotlib.pyplot as plt

    df = pd.read_excel("training.xls")

    fig = plt.figure()
    ax = fig.add_subplot(111)

    boxprops = dict(color="black",linewidth=1.5)
    medianprops = dict(color="black",linewidth=1.5)


    df.boxplot(column=["MEAN"],by="SrcID_Feat",ax=ax,
              boxprops=boxprops,medianprops=medianprops)

    plt.grid(False)

Result

Screen Shot

标签: python-3.xmatplotlibjupyter-notebook

解决方案


我发现除非我添加参数patch_artist=True,否则 boxprops 字典都不会对箱线图产生任何影响。例如,当我生成一个将 facecolor 更改为黄色的箱线图时,我必须使用以下编码:

plt.boxplot(boxplot_data, positions=[1], patch_artist=True, boxprops=dict(facecolor='yellow'), showmeans=True)

推荐阅读