首页 > 解决方案 > 箱线图中的多种传单颜色

问题描述

我想设置多种传单颜色并有一个图例。我当前的代码如下:例如,从该代码给出的输出中,我想将 2020 年的一个传单设置为不同的颜色。有谁知道如何做到这一点?谢谢!

import matplotlib.pyplot as plt

fig, ax = plt.subplots()
boxes = [
    {
        'label' : "2020",
        'whislo': 1.49,    # Bottom whisker position
        'q1'    : 9.36,    # First quartile (25th percentile)
        'med'   : 14.21,    # Median         (50th percentile)
        'q3'    : 18.73,    # Third quartile (75th percentile)
        'whishi': 54.76,    # Top whisker position
        'fliers': [10.7, 9.4]        # Outliers
    },
    {
        'label' : "2019",
        'whislo': 0.63,    # Bottom whisker position
        'q1'    : 6.11,    # First quartile (25th percentile)
        'med'   : 9.66,    # Median         (50th percentile)
        'q3'    : 15.33,    # Third quartile (75th percentile)
        'whishi': 23.89,    # Top whisker position
        'fliers': [2.8, 9.7]        # Outliers
    },
        {
        'label' : "2018",
        'whislo': -8.19,    # Bottom whisker position
        'q1'    : -0.15,    # First quartile (25th percentile)
        'med'   : 2.66,    # Median         (50th percentile)
        'q3'    : 7.85,    # Third quartile (75th percentile)
        'whishi': 13.25,    # Top whisker position
        'fliers': [8.6]        # Outliers
    },
            {
        'label' : "2017",
        'whislo': 3.51,    # Bottom whisker position
        'q1'    : 7.74,    # First quartile (25th percentile)
        'med'   : 10.91,    # Median         (50th percentile)
        'q3'    : 15.04,    # Third quartile (75th percentile)
        'whishi': 22.47,    # Top whisker position
        'fliers': [15.3]        # Outliers
    },
                {
        'label' : "2016",
        'whislo': -3.92,    # Bottom whisker position
        'q1'    : 0.05,    # First quartile (25th percentile)
        'med'   : 3.79,    # Median         (50th percentile)
        'q3'    : 7.60,    # Third quartile (75th percentile)
        'whishi': 14.65,    # Top whisker position
        'fliers': [0.4]        # Outliers
    }
]
ax.bxp(boxes, showfliers=True, flierprops={'markerfacecolor':'fuchsia', 'marker':'o'})

plt.ylim([-10,65])
plt.show()

标签: pythonmatplotlib

解决方案


最简单的方法是再次绘制该点(使用1x 位置,这是第一个框的默认 x 位置)。例如 ax.plot(1, 10.7, marker='o', markerfacecolor='lime')。要将这一点标记在图例中,ax.plot(...., label=...)可以使用。

像许多 matplotlib 函数一样,ax.bxp返回有关创建的图形元素的信息。在这种情况下,它是一个字典,带有一个条目'fliers',通向一个列表。这里的每个条目又是一个点列表,每个框一个列表。例如,您可以使用box_info['fliers'][0].set_color('turquoise')来更改属于第一个框的所有传单的颜色。同样,.set_label(...)可用于在图例中添加条目。

from matplotlib import pyplot as plt

fig, ax = plt.subplots()
box_info = ax.bxp(boxes, showfliers=True, flierprops={'markerfacecolor': 'fuchsia', 'marker': 'o'})
box_info['fliers'][-1].set_label('Outliers')
ax.plot(1, 10.7, marker='o', markerfacecolor='lime', linestyle='', label='Special outlier')
ax.legend()
ax.set_ylim([-10, 65])
plt.show()

带有特殊异常值和自定义图例的箱线图


推荐阅读