python - 箱线图中的多种传单颜色
问题描述
我想设置多种传单颜色并有一个图例。我当前的代码如下:例如,从该代码给出的输出中,我想将 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()
解决方案
最简单的方法是再次绘制该点(使用1
x 位置,这是第一个框的默认 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()
推荐阅读
- azure - 使用 AAD 身份验证将 Blazor 应用部署到 Azure
- git - 如何在 docker 中使用 keybase 的 git?
- c++ - 将表情符号字符串转换为 icu::UnicodeString
- java - compareTo() 抛出空指针异常
- php - 如何在php中的单个变量中添加3个下拉菜单?
- java - 'while' 无限循环使用扫描仪输入和 pos/neg 数字
- python-3.x - 如何在 Python 中为每一行数据框创建唯一的 XML
- asp.net-core - 将 JWT 令牌存储在内存中是否是一种好习惯
- c++ - 如何使用 CMake 自动链接 boost 库
- c - C、为什么我的自定义释放函数给我“指针被释放没有分配”错误