Files
notes_estom/Python/matplotlab/gallery/statistics/customized_violin.md
2020-09-26 22:03:11 +08:00

75 lines
2.6 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# 自定义小提琴图
此示例演示如何完全自定义小提琴图。 第一个图通过仅提供数据来显示默认样式。第二个图首先限制了matplotlib用额外的kwargs绘制的内容。然后在顶部绘制箱形图的简化表示。 最后,修改了小提琴图的风格。
有关小提琴图的更多信息scikit-learn文档有一个很棒的部分http://scikit-learn.org/stable/modules/density.html
![自定义小提琴图示例](https://matplotlib.org/_images/sphx_glr_customized_violin_001.png)
```python
import matplotlib.pyplot as plt
import numpy as np
def adjacent_values(vals, q1, q3):
upper_adjacent_value = q3 + (q3 - q1) * 1.5
upper_adjacent_value = np.clip(upper_adjacent_value, q3, vals[-1])
lower_adjacent_value = q1 - (q3 - q1) * 1.5
lower_adjacent_value = np.clip(lower_adjacent_value, vals[0], q1)
return lower_adjacent_value, upper_adjacent_value
def set_axis_style(ax, labels):
ax.get_xaxis().set_tick_params(direction='out')
ax.xaxis.set_ticks_position('bottom')
ax.set_xticks(np.arange(1, len(labels) + 1))
ax.set_xticklabels(labels)
ax.set_xlim(0.25, len(labels) + 0.75)
ax.set_xlabel('Sample name')
# create test data
np.random.seed(19680801)
data = [sorted(np.random.normal(0, std, 100)) for std in range(1, 5)]
fig, (ax1, ax2) = plt.subplots(nrows=1, ncols=2, figsize=(9, 4), sharey=True)
ax1.set_title('Default violin plot')
ax1.set_ylabel('Observed values')
ax1.violinplot(data)
ax2.set_title('Customized violin plot')
parts = ax2.violinplot(
data, showmeans=False, showmedians=False,
showextrema=False)
for pc in parts['bodies']:
pc.set_facecolor('#D43F3A')
pc.set_edgecolor('black')
pc.set_alpha(1)
quartile1, medians, quartile3 = np.percentile(data, [25, 50, 75], axis=1)
whiskers = np.array([
adjacent_values(sorted_array, q1, q3)
for sorted_array, q1, q3 in zip(data, quartile1, quartile3)])
whiskersMin, whiskersMax = whiskers[:, 0], whiskers[:, 1]
inds = np.arange(1, len(medians) + 1)
ax2.scatter(inds, medians, marker='o', color='white', s=30, zorder=3)
ax2.vlines(inds, quartile1, quartile3, color='k', linestyle='-', lw=5)
ax2.vlines(inds, whiskersMin, whiskersMax, color='k', linestyle='-', lw=1)
# set style for the axes
labels = ['A', 'B', 'C', 'D']
for ax in [ax1, ax2]:
set_axis_style(ax, labels)
plt.subplots_adjust(bottom=0.15, wspace=0.05)
plt.show()
```
## 下载这个示例
- [下载python源码: customized_violin.py](https://matplotlib.org/_downloads/customized_violin.py)
- [下载Jupyter notebook: customized_violin.ipynb](https://matplotlib.org/_downloads/customized_violin.ipynb)