特殊图表综合应用

等高线、流线、甘特图、桑基图……用更丰富的图表语言呈现复杂数据关系。

等高线流线图甘特图桑基图华夫饼图
气象气压分布等高线

图表作品

共 10 张图表 · 点击图片可放大,展开可查看完整代码

01

气象气压分布等高线

用 contourf 与 contour 绘制填充等高线,并添加数值标签与色条。

查看 Python 代码 +
import numpy as np
import matplotlib.pyplot as plt
plt.rcParams["font.sans-serif"] = ["SimHei"]
plt.rcParams["axes.unicode_minus"] = False
x = np.linspace(-5, 5, 100)
y = np.linspace(-5, 5, 100)
X, Y = np.meshgrid(x, y)
Z = np.sin(X) + np.cos(Y)
plt.figure(figsize=(8, 6))
contourf = plt.contourf(
    X, Y, Z,
    levels=15,
    cmap='coolwarm'
)
contour = plt.contour(
    X, Y, Z,
    levels=15,
    colors='black',
    linewidths=0.5
)
plt.clabel(contour, inline=True, fontsize=8)
plt.colorbar(contourf, label='气压值')
plt.title('气象气压分布(等高线图)')
plt.xlabel('X')
plt.ylabel('Y')
plt.show()
02

液体涡流流线图

用 streamplot 表现向量场,线宽与颜色映射流速大小。

查看 Python 代码 +
import numpy as np
import matplotlib.pyplot as plt
plt.rcParams["font.sans-serif"] = ["SimHei"]
plt.rcParams["axes.unicode_minus"] = False
y, x = np.mgrid[-3:3:50j, -3:3:50j]
u = -y
v = x
speed = np.sqrt(u**2 + v**2)
linewidth = 0.5 + 2.5 * speed / speed.max()
fig, ax = plt.subplots(figsize=(8, 6))
ax = fig.add_subplot(111)
stream = ax.streamplot(
    x, y, u, v,
    color=speed,
    cmap='plasma',
    linewidth=linewidth,
    density=1.5,
    arrowsize=1
)
plt.colorbar(stream.lines, ax=ax, label='流速')
ax.set_title("液体涡流模型(流线图)")
plt.show()
03

股票收益率棉棒图

用 stem 绘制每日收益的正负变化,并添加零轴参考线。

查看 Python 代码 +
import numpy as np
import matplotlib.pyplot as plt
plt.rcParams["font.sans-serif"] = ["SimHei"]
plt.rcParams["axes.unicode_minus"] = False
days = np.arange(1, 11)
returns = np.array([
    1.2, -0.5, 0.8, 2.3, -1.5,
    -0.2, 1.0, 3.5, -2.0, 0.0
])
plt.figure(figsize=(10, 5))
plt.stem(
    days,
    returns,
    linefmt='gray',
    markerfmt='bs',
    basefmt='r--'
)
plt.axhline(0, color='red', linestyle='--')
plt.title('股票收益率波动(棉棒图)')
plt.xlabel('天数')
plt.ylabel('收益率(%)')
plt.grid(alpha=0.3)
plt.show()
04

员工培训哑铃图

用线段连接培训前后分数,突出进步幅度较大的员工。

查看 Python 代码 +
import numpy as np
import matplotlib.pyplot as plt
plt.rcParams["font.sans-serif"] = ["SimHei"]
plt.rcParams["axes.unicode_minus"] = False
names = ['张三', '李四', '王五', '赵六', '孙七']
before = np.array([60, 72, 55, 80, 65])
after = np.array([85, 75, 88, 82, 90])
y = np.arange(len(names))
plt.figure(figsize=(10, 5))

for i in range(len(names)):
    improvement = after[i] - before[i]
    if improvement > 20:
        color = 'red'
    else:
        color = 'lightblue'

    plt.plot(
        [before[i], after[i]],
        [y[i], y[i]],
        color=color,
        linewidth=2.5
    )
plt.scatter(before, y, color='gray', label='培训前', s=100)
plt.scatter(after, y, color='green', label='培训后', s=100)
plt.yticks(y, names)
plt.xlim(55, 92)
plt.xlabel('考核分数')
plt.title('员工技能培训考核(哑铃图)')
plt.legend()
plt.grid(axis='x', alpha=0.3)
plt.show()
05

新产品发布甘特图

用水平条形图表示任务起止时间与持续天数,呈现项目进度。

查看 Python 代码 +
import numpy as np
import matplotlib.pyplot as plt
plt.rcParams["font.sans-serif"] = ["SimHei"]
plt.rcParams["axes.unicode_minus"] = False
tasks = ['市场调研', '产品设计', '原型开发', '内部测试', '正式发布']
start = [1, 5, 10, 20, 28]
duration = [4, 5, 10, 7, 2]
y = np.arange(len(tasks))
fig, ax = plt.subplots(figsize=(10, 6))
ax.barh(
    y,
    duration,
    left=start,
    color='forestgreen',
    edgecolor='black',
    height=0.6
)
for i in range(len(tasks)):
    ax.text(
        start[i] + duration[i] / 2,
        y[i],
        str(duration[i]) + '天',
        ha='center',
        va='center',
        color='white'
    )
ax.set_yticks(y)
ax.set_yticklabels(tasks)
ax.invert_yaxis()
ax.set_xlabel('项目天数')
ax.set_title('新产品发布流程(甘特图)')
ax.set_xticks(np.arange(5, 31, 5))
ax.grid(axis='x', linestyle='--', alpha=0.4)
plt.show()
06

城市人口结构金字塔

用左右对称的双向条形图对比各年龄段男女人口。

查看 Python 代码 +
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.ticker import FuncFormatter
plt.rcParams["font.sans-serif"] = ["SimHei"]
plt.rcParams["axes.unicode_minus"] = False
ages = ['0-19', '20-29', '30-39', '40-49', '50+']
male = np.array([10, 35, 40, 20, 15])
female = np.array([9, 30, 38, 18, 16])
y = np.arange(len(ages))
fig, ax = plt.subplots(figsize=(10, 6))
ax.barh(
    y, -male,
    color='cornflowerblue',
    label='男性'
)
ax.barh(
    y, female,
    color='palevioletred',
    label='女性'
)
ax.xaxis.set_major_formatter(
    FuncFormatter(lambda x, pos: str(abs(int(x))))
)
ax.set_yticks(y)
ax.set_yticklabels(ages)
ax.set_xlabel('人口数量(万人)')
ax.set_title('城市人口结构(人口金字塔)')
ax.axvline(0, color='black', linewidth=0.8)
ax.legend()
ax.grid(axis='x', alpha=0.3)
plt.show()
07

销售转化漏斗图

以居中对称的条形宽度表示各阶段客户数量与转化率。

查看 Python 代码 +
import numpy as np
import matplotlib.pyplot as plt
plt.rcParams["font.sans-serif"] = ["SimHei"]
plt.rcParams["axes.unicode_minus"] = False
stages = ['潜在客户', '初步沟通', '方案演示', '商务谈判', '赢单']
values = np.array([5000, 2500, 1000, 500, 200])
percent = values / values[0] * 100
width = percent
left = -width / 2
y = np.arange(len(stages))
fig, ax = plt.subplots(figsize=(10, 6))
ax.barh(
    y,
    width,
    left=left,
    height=0.7,
    color='orange',
    edgecolor='gray',
    alpha=0.8
)
for i in range(len(values)):
    ax.text(
        0,
        y[i],
        f'{values[i]}\n{percent[i]:.1f}%',
        ha='center',
        va='center',
        color='white',
        fontsize=10
    )
for i in range(len(values) - 1):

    right1 = width[i] / 2
    right2 = width[i + 1] / 2

    left1 = -width[i] / 2
    left2 = -width[i + 1] / 2

    ax.plot(
        [right1, right2],
        [y[i], y[i+1]],
        '--o',
        color='gray',
        markersize=4
    )

    ax.plot(
        [left1, left2],
        [y[i], y[i+1]],
        '--o',
        color='gray',
        markersize=4
    )
ax.set_yticks(y)
ax.set_yticklabels(stages)
ax.invert_yaxis()
ax.set_xticks([])
ax.set_title('2023 Q4 销售转化漏斗')
plt.show()
08

家庭月度收支桑基图

用 Sankey 图展示收入来源与各项支出的流向关系。

查看 Python 代码 +
import matplotlib.pyplot as plt
from matplotlib.sankey import Sankey
plt.rcParams["font.sans-serif"] = ["SimHei"]
plt.rcParams["axes.unicode_minus"] = False
flows =[10000, 2000, -4000, -3000, -1000, -4000]
labels =  ["工资", "奖金", "房租", "餐饮", "交通", "储蓄"]
orientations = [1,-1,-1,0,-1,-1]
fig, ax = plt.subplots(figsize=(10, 6))
sankey = Sankey(
    ax=ax,
    scale=0.00008,
    gap=0.45,
    radius=0.12,
    shoulder=0.08,
    margin=0.4
)
sankey.add(flows=flows,                     
           labels=labels,                   
           orientations=orientations,      
           color="black",                   
           fc="skyblue",                 
           patchlabel="家庭月度收支",        
           linewidth=1.5,
           alpha=0.85) 
diagrams = sankey.finish()
diagrams[0].texts[5].set_color("r")         
diagrams[0].texts[5].set_weight("bold")     
diagrams[0].text.set_fontsize(20)          
diagrams[0].text.set_fontweight("bold")     
plt.title("家庭月度收支流向的桑基图", fontsize=16, pad=20)
ax.axis("off")
plt.tight_layout()
plt.show()
09

商品相似度树状图

用层次聚类树状图展示六个商品之间的相似关系。

查看 Python 代码 +
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import scipy.cluster.hierarchy as shc
plt.rcParams["font.sans-serif"] = ["SimHei"]
plt.rcParams["axes.unicode_minus"] = False
df = np.random.rand(6,2)
labels = ['A','B','C','D','E','F']
Z = shc.linkage(df, method='ward')
plt.figure(figsize=(10, 6), dpi= 80)
plt.title("商品相似度聚类的树状图", fontsize=12)
shc.dendrogram(
    Z,
    labels=labels
)
plt.xlabel("商品")
plt.ylabel("距离")
plt.xticks(fontsize=10)
plt.show()
10

课余时间华夫饼图

用 10×10 的方块矩阵展示大学生课余时间的分配比例。

查看 Python 代码 +
import matplotlib.pyplot as plt
from pywaffle import Waffle
plt.rcParams["font.sans-serif"] = ["SimHei"]
plt.rcParams["axes.unicode_minus"] = False
data = {
    '社团活动': 30,
    '兼职': 20,
    '自习': 40,
    '娱乐': 10
}
colors = ['orange', 'green', 'dodgerblue', 'purple']
fig = plt.figure(
    FigureClass=Waffle,
    rows=10,
    columns=10,
    values=data,
    colors=colors,
    title={'label': '大学生课余时间分配(华夫饼图)'},
    legend={
        'loc': 'lower center',
        'bbox_to_anchor': (0.5, -0.1),
        'ncol': 4
    }
)
plt.show()