Matplotlib | 高阶绘图案例【2】- 读哪些专业最容易后悔

73 阅读2分钟

大家好,我是 👉 【Python当打之年】

本期是 Matplotlib高阶绘图案例系列 的第 2 期,Matplotlib系列和Pyecharts系列都会不间断更新,希望对大家有所帮助,如有疑问或者需要改进的地方可以联系小编。

上期Matplotlib | 高阶绘图案例【1】

先看看效果:

图片

1. 导入模块

import numpy as np
import matplotlib.pyplot as plt
import funcy
import warnings
warnings.filterwarnings('ignore')
plt.rcParams['font.family'] = ['Microsoft YaHei']

示例数据:

majors = ['营销''金融''心理学''新闻学''电视''日语''汉语言''物理''机械''文学''生物''计算机''化学''数学''设计''英语''会计''教育''工程''医学']
datas = [18.721.622.923.524.826.227.127.129.631.332.633.536.340.854.355.870.170.370.7100]

2. 绘图

2.1 绘制图布,设置极坐标系

fig, ax = plt.subplots(figsize=(1212),dpi=100)
ax1 = fig.add_axes([0.220.20.60.6], polar=True)

图片

2.2 绘制上半扇形区域

theta_group = np.linspace(0121)*np.pi
# 绘制上半扇形区域
for idx, group in enumerate(funcy.pairwise(theta_group)):
    ax1.fill_between(group, 1.44, facecolor='#fafbff' if idx % 2 == 0 else '#e3effd')

图片

2.3 绘制上半扇形区域中间虚线

# 绘制虚线
for idx, group in enumerate(funcy.pairwise(theta_group)):
    theta = (group[0] + group[1]) / 2
    ax1.plot([theta, theta], [1.43.5], linestyle='dashed', color='#9fa0a0', linewidth=0.25)

图片

2.4 绘制柱状图

for idx, group in enumerate(funcy.pairwise(theta_group)):
    theta = (group[0] + group[1]) / 2
    ax1.plot([theta, theta], [1.43.5], linestyle='dashed', color='#9fa0a0', linewidth=0.25)
    # 柱状图
    ax1.bar(theta, 0.025*datas[idx], width=[np.pi / 21], bottom=1.4,
            facecolor='#6785f2' if idx % 2 == 0 else '#7171fe', edgecolor='white', linewidth=0.1, alpha=0.95, zorder=9
           )

图片

2.5 绘制扇形区域白色边界

# 绘制扇形区域白色边界
for theta in theta_group:
    ax1.plot([theta, theta], [1, 4], color='w', linewidth=0.5)

图片

2.6 添加文本指数

# 文本
for idx, group in enumerate(funcy.pairwise(theta_group)): # 文字角度
    angle = ((group[0] + group[1]) * 0.5 / np.pi) * 180 - (0 if idx < (len(majors) / 2else 180)
    # 专业
    ax1.annotate(majors[idx], xy=[(group[0]+group[1]) / 24.4], va='center', ha='center', zorder=10, rotation=angle,fontsize=10)
    # 指数
    ax1.annotate(datas[idx],
                 xy=[(group[0]+group[1]) / 23.79],
                 va='center', ha='center', zorder=10,
                 rotation=angle,
                 fontsize=10)

图片

2.7 绘制外圈虚线

# 绘制外圈虚线
ax1.plot([00], [1.44.8], linestyle='--', color='#B0BEC5', linewidth=0.25)
ax1.plot([np.pi, np.pi], [1.44.8], linestyle='--', color='#B0BEC5', linewidth=0.25)
ax1.plot(np.linspace(011000)*np.pi, [4.8]*1000, linestyle='dashed', color='#B0BEC5', linewidth=0.75)

图片

2.8 添加标题

ax1.annotate('在网友看来\n读哪些专业', xy=[np.pi/20.9],
             va='center',ha='center', zorder=10,
             fontsize=12,fontproperties='Microsoft Yahei', fontweight='bold'
            )

ax1.annotate('最容易后悔?', xy=[np.pi/20.4],
             va='center',ha='center', ma='center',zorder=10,
             fontsize=16,color='#D32F2F', fontproperties='Microsoft Yahei', fontweight='bold',
            )

图片

在线运行地址

www.heywhale.com/mw/project/…