ZetCode

Matplotlib 区域图

最后修改于 2025 年 2 月 25 日

Matplotlib 是一个功能强大的 Python 库,用于创建静态、动画和交互式可视化。区域图对于可视化累积数据或随时间比较多个数据集非常有用。本教程涵盖了如何使用 Matplotlib 创建各种类型的区域图。

区域图非常适合展示趋势和累计总数,例如随时间变化的收入或资源使用情况。Matplotlib 提供了一个灵活且易于使用的界面,用于创建可自定义的区域图。

基本区域图

本示例演示了如何使用月度网站流量数据创建基本区域图。

basic_area_chart.py
import matplotlib.pyplot as plt

# Data: Months and website visitors (in thousands)
months = ["Jan", "Feb", "Mar", "Apr", "May"]
visitors = [50, 60, 80, 75, 90]

# Create an area chart
plt.fill_between(months, visitors, color="skyblue", alpha=0.4)
plt.plot(months, visitors, color="blue", label="Visitors")

# Add labels, title, and legend
plt.xlabel("Month")
plt.ylabel("Visitors (thousands)")
plt.title("Website Traffic in 2025")
plt.legend()

# Display the chart
plt.show()

在此示例中,我们可视化了 2025 年五个月的网站访问者数量。plt.fill_between 函数填充了线条下方的区域,表示累计访问者数量。alpha=0.4 参数设置了透明度,使填充的颜色足够浅,可以与线条区分开,但仍然可见。折线图覆盖了填充区域,以强调趋势。

这种图表类型有助于跟踪随时间变化的简单指标,例如网站流量、销售额或温度变化。在此,数据反映了一个真实场景:流量在三月份增加,四月份略有下降,然后在五月份达到顶峰——这通常是在现实世界的分析中由于季节性趋势或营销活动而出现的模式。

堆叠区域图

本示例展示了如何创建堆叠区域图以比较不同产品类别的销售情况。

stacked_area_chart.py
import matplotlib.pyplot as plt

# Data: Months and sales (in thousands of dollars)
months = ["Jan", "Feb", "Mar", "Apr", "May"]
electronics = [30, 35, 40, 45, 50]
clothing = [20, 25, 30, 28, 35]

# Create a stacked area chart
plt.stackplot(months, electronics, clothing, labels=["Electronics", "Clothing"], colors=["skyblue", "lightgreen"])

# Add labels, title, and legend
plt.xlabel("Month")
plt.ylabel("Sales (thousands $)")
plt.title("Product Sales in 2025")
plt.legend()

# Display the chart
plt.show()

在这里,我们使用 plt.stackplot 创建了一个堆叠区域图,显示了电子产品和服装两大类产品在五个月内的销售数据。该图堆叠了销售数值,使我们能够看到每个类别的单独贡献以及总销售趋势。labels 参数为每个数据集命名,colors 列表为清晰起见分配了不同的颜色。

这种可视化方法在比较多个类别随时间变化的相对表现方面特别有效。例如,电子产品的销售额持续高于服装,但两个类别都显示出增长,并在三月份出现显著增长——可能由于春季促销。此类见解对于分析收入流或规划库存的企业非常有价值。

含负值的区域图

本示例演示了如何创建带有盈亏数据(包括负值)的区域图。

negative_area_chart.py
import matplotlib.pyplot as plt

# Data: Months and profit/loss (in thousands of dollars)
months = ["Jan", "Feb", "Mar", "Apr", "May"]
profit_loss = [10, -5, 15, -8, 12]

# Create an area chart with negative values
plt.fill_between(months, profit_loss, color="skyblue", alpha=0.4)
plt.plot(months, profit_loss, color="blue", label="Profit/Loss")

# Add labels, title, and legend
plt.xlabel("Month")
plt.ylabel("Profit/Loss (thousands $)")
plt.title("Monthly Profit/Loss in 2025")
plt.legend()

# Display the chart
plt.show()

此图跟踪企业的月度盈亏,其中负值表示亏损。plt.fill_between 函数会自动调整,在负值下方填充到 x 轴,从而清晰地区分盈利和亏损期。折线图有助于突出显示确切的数值和趋势方向。

在此示例中,二月和四月出现亏损(分别为 -5 和 -8 千美元),而其他月份则盈利。这种类型的图表对于财务分析非常有用,因为了解收益和挫折都至关重要——例如,识别受意外支出或销售不佳影响的月份。即使有负区域,透明度也能确保可读性。

带渐变填充的区域图

本示例展示了如何使用每日温度数据创建带渐变填充的区域图。

gradient_area_chart.py
import matplotlib.pyplot as plt
import numpy as np

# Data: Days and temperature (in Celsius)
days = np.arange(1, 31)  # 30 days in April
temp = 15 + 5 * np.sin(np.linspace(0, 2 * np.pi, 30))  # Simulated temperature

# Create an area chart with gradient fill
plt.fill_between(days, temp, color="skyblue", alpha=0.4, interpolate=True)
plt.plot(days, temp, color="blue", label="Temperature")

# Add labels, title, and legend
plt.xlabel("Day in April")
plt.ylabel("Temperature (°C)")
plt.title("Daily Temperature in April 2025")
plt.legend()

# Display the chart
plt.show()

此示例使用了模拟的 2025 年 4 月每日温度数据,这些数据是通过正弦波生成的,以模仿自然波动。np.linspacenp.sin 函数创建了平滑的数据集,而带有 interpolate=Trueplt.fill_between 确保了曲线下方平滑的渐变填充。基本温度设置为 15°C,变化为 5°C。

渐变填充增强了视觉吸引力,使其更容易看到整个月的温度趋势。这种类型的图表可用于气象学或环境研究,以引人入胜的方式呈现连续数据。平滑插值对于密集数据集尤其有用,可以避免锯齿状边缘并反映真实的每日温度变化。

多层区域图

本示例演示了如何使用能源消耗数据创建多层区域图。

multi_layer_area_chart.py
import matplotlib.pyplot as plt

# Data: Months and energy consumption (in GWh)
months = ["Jan", "Feb", "Mar", "Apr", "May"]
residential = [120, 130, 110, 100, 115]
industrial = [200, 210, 220, 215, 230]
commercial = [80, 85, 90, 88, 95]

# Create an area chart with multiple layers
plt.fill_between(months, residential, color="skyblue", alpha=0.4, label="Residential")
plt.fill_between(months, industrial, color="lightgreen", alpha=0.4, label="Industrial")
plt.fill_between(months, commercial, color="orange", alpha=0.4, label="Commercial")

# Add labels, title, and legend
plt.xlabel("Month")
plt.ylabel("Energy Consumption (GWh)")
plt.title("Energy Consumption by Sector in 2025")
plt.legend()

# Display the chart
plt.show()

此图显示了五个月内住宅、工业和商业三个部门的能源消耗。每个部门通过单独的 plt.fill_between 调用表示,创建了重叠的层。alpha=0.4 参数确保了透明度,即使在重叠时也能看到所有层,而不同的颜色则区分了各个部门。

与堆叠图不同,这种分层方法不累积值,而是独立显示每个数据集。在此,工业用电量占主导地位,在五月份达到 230 GWh 的峰值,而住宅和商业用电量显示出较小的波动。这种可视化方法有助于能源分析师比较绝对消耗模式,而无需汇总总数。

带基线调整的区域图

本示例演示了如何使用股票价格数据创建带调整基线的区域图。

baseline_area_chart.py
import matplotlib.pyplot as plt

# Data: Days and stock prices (in dollars)
days = ["Mon", "Tue", "Wed", "Thu", "Fri"]
prices = [150, 152, 148, 155, 160]

# Create an area chart with a custom baseline
plt.fill_between(days, prices, 145, color="skyblue", alpha=0.4, label="Price Variation")
plt.plot(days, prices, color="blue", label="Stock Price")

# Add labels, title, and legend
plt.xlabel("Day")
plt.ylabel("Price ($)")
plt.title("Stock Price Variation (Week of March 3, 2025)")
plt.legend()

# Display the chart
plt.show()

此图跟踪了一周内的股票价格,填充区域位于价格线和 145 美元的基线之间。plt.fill_between 函数接受基线值(此处为 145)作为第二个参数,在该值和数据点之间填充区域。这突出了相对于参考点(如开盘价或平均值)的价格变化。

在此示例中,股票在周三跌破 150 美元,但在周五上涨至 160 美元。将基线设为 145 美元显示了相对于该阈值的收益和损失,这可能代表了交易者的关键水平。这种变化在金融分析或任何偏离常态的偏差比绝对值更有洞察力的场景中都很有用。

带双 Y 轴的区域图

本示例演示了如何创建带双 Y 轴的区域图,以比较月度降雨量和温度。

dual_axes_area_chart.py
import matplotlib.pyplot as plt

# Data: Months, rainfall (mm), and temperature (°C)
months = ["Jan", "Feb", "Mar", "Apr", "May"]
rainfall = [80, 60, 40, 50, 70]
temperature = [15, 16, 18, 20, 22]

# Create figure and twin axes
fig, ax1 = plt.subplots()
ax2 = ax1.twinx()

# Plot rainfall on first axis
ax1.fill_between(months, rainfall, color="skyblue", alpha=0.4, label="Rainfall")
ax1.plot(months, rainfall, color="blue")
ax1.set_xlabel("Month")
ax1.set_ylabel("Rainfall (mm)", color="blue")
ax1.tick_params(axis="y", labelcolor="blue")

# Plot temperature on second axis
ax2.fill_between(months, temperature, color="lightcoral", alpha=0.4, label="Temperature")
ax2.plot(months, temperature, color="red")
ax2.set_ylabel("Temperature (°C)", color="red")
ax2.tick_params(axis="y", labelcolor="red")

# Add title and legend
plt.title("Rainfall and Temperature in 2025")
fig.legend(loc="upper center", bbox_to_anchor=(0.5, -0.05), ncol=2)

# Display the chart
plt.show()

此示例使用双 Y 轴比较 2025 年五个月的月度降雨量和平均温度。plt.subplots() 函数创建了一个图形和主轴 (ax1),而 twinx() 生成了一个共享同一 X 轴的次轴 (ax2)。降雨量以蓝色绘制在左侧 Y 轴上,温度以红色绘制在右侧 Y 轴上,并具有匹配的填充颜色和透明度 (alpha=0.4)。

双轴方法非常适合可视化具有不同单位或尺度的两个数据集,例如天气指标。在此,降雨量在一月份达到顶峰(80 毫米),在三月份下降(40 毫米),而温度从 15°C 稳步上升到 22°C。颜色编码的标签和刻度增强了可读性,图例位于图表下方以保持清晰。此图可以帮助气象学家或农民有效分析季节性模式。

累积区域图

本示例展示了如何创建累积区域图以跟踪随时间变化的累计销售额。

cumulative_area_chart.py
import matplotlib.pyplot as plt
import numpy as np

# Data: Months and monthly sales (in thousands of dollars)
months = ["Jan", "Feb", "Mar", "Apr", "May"]
monthly_sales = [20, 25, 30, 28, 35]

# Calculate cumulative sales
cumulative_sales = np.cumsum(monthly_sales)

# Create a cumulative area chart
plt.fill_between(months, cumulative_sales, color="skyblue", alpha=0.4)
plt.plot(months, cumulative_sales, color="blue", label="Cumulative Sales")

# Add labels, title, and legend
plt.xlabel("Month")
plt.ylabel("Cumulative Sales (thousands $)")
plt.title("Cumulative Sales in 2025")
plt.legend()

# Display the chart
plt.show()

在此示例中,我们可视化了 2025 年五个月的业务累计销售额。np.cumsum 函数计算月度销售额的累积总和,将 [20, 25, 30, 28, 35] 转换为 [20, 45, 75, 103, 138]。然后,plt.fill_between 函数填充该累积曲线下方的区域,并通过一个折线图覆盖它以显示增长轨迹。

累积区域图非常适合跟踪目标的进展情况,例如年度销售目标。在此,销售额稳步增长,到五月份达到 138,000 美元,其中三月份的月度增长最大(30)。填充区域突出了总累积量,可以轻松查看每个月如何为总体数字做出贡献——这对于监控业绩的业务所有者或财务分析师非常有用。

带注释的区域图

本示例演示了如何创建带注释的区域图,以突出社交媒体粉丝增长中的关键事件。

annotated_area_chart.py
import matplotlib.pyplot as plt

# Data: Weeks and followers (in thousands)
weeks = ["Week 1", "Week 2", "Week 3", "Week 4", "Week 5"]
followers = [10, 12, 18, 20, 25]

# Create an area chart
plt.fill_between(weeks, followers, color="skyblue", alpha=0.4)
plt.plot(weeks, followers, color="blue", label="Followers")

# Add annotations
plt.annotate("Viral Post", xy=("Week 3", 18), xytext=("Week 2", 20),
             arrowprops=dict(facecolor="black", shrink=0.05))
plt.annotate("Campaign Launch", xy=("Week 5", 25), xytext=("Week 4", 27),
             arrowprops=dict(facecolor="black", shrink=0.05))

# Add labels, title, and legend
plt.xlabel("Week")
plt.ylabel("Followers (thousands)")
plt.title("Social Media Follower Growth in 2025")
plt.legend()

# Display the chart
plt.show()

此图跟踪了五周内的社交媒体粉丝增长情况,并附有注释以标记重要事件。plt.fill_between 函数填充了粉丝数量曲线下方的区域,而 plt.annotate 添加了文本标签和指向关键数据点的箭头:第三周的病毒式帖子(18,000 名粉丝)和第五周的营销活动启动(25,000 名粉丝)。

注释通过解释粉丝数量的突然增加(例如,由于病毒式帖子,粉丝数从第三周的 12,000 增加到 18,000)使此图更具信息量。xy 参数设置了注释的锚点,xytext 调整了其文本位置,并用箭头连接它们。这种变化对于分析特定活动对受众增长影响的市场营销团队或内容创作者来说非常理想。

区域图最佳实践

来源

Matplotlib 区域图文档

在本文中,我们探讨了使用 Matplotlib 的各种区域图类型,包括基本、堆叠、负值、渐变、多层和基线调整的区域图。

作者

我叫 Jan Bodnar,是一位充满热情的程序员,拥有丰富的编程经验。自 2007 年以来,我一直在撰写编程文章。至今,我已撰写了 1400 多篇文章和 8 本电子书。我在教授编程方面拥有十多年的经验。

列出 所有 Python 教程