python 多色箱形图
时间: 2023-10-30 12:07:46 浏览: 40
要在Python中创建多色箱形图,可以按照以下步骤进行操作:
1. 导入必要的库:
```python
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
```
2. 生成数据并创建DataFrame对象:
```python
np.random.seed(2)
df = pd.DataFrame(np.random.rand(5, 4), columns=['A', 'B', 'C', 'D'])
```
3. 绘制箱形图并设置返回类型为字典:
```python
f = df.boxplot(patch_artist=True, return_type='dict')
```
4. 设置颜色数组,并使用循环为每个箱体设置边框颜色和填充颜色:
```python
color = ['k', 'g', 'r', 'deepskyblue']
for box, c in zip(f['boxes'], color):
box.set(color=c, linewidth=2) # 箱体边框颜色
box.set(facecolor=c) # 箱体内部填充颜色
```
5. 设置其他箱体属性,如须位、边缘线、中位数和异常值:
```python
for whisker in f['whiskers']:
whisker.set(color='r', linewidth=2)
for cap in f['caps']:
cap.set(color='g', linewidth=3)
for median in f['medians']:
median.set(color='DarkBlue', linewidth=3)
for flier in f['fliers']:
flier.set(marker='o', color='y', alpha=0.5)
```
6. 显示图形:
```python
plt.show()
```
这样,你就可以创建一个多色箱形图了。