ZetCode

Matplotlib 图表样式

最后修改于 2025 年 3 月 7 日

Matplotlib 提供了丰富的样式选项来自定义图表,增强其视觉吸引力和清晰度。本教程涵盖连接样式、端盖样式、线条样式、颜色、渐变等,并提供实用示例。

样式是有效数据可视化的关键,使图表更易于阅读和理解。从线条图案到颜色渐变,Matplotlib 提供了定制图表的工具以满足特定需求,例如报告或演示文稿。

连接样式和端盖样式

此示例使用连接和端盖样式来设置温度折线图的样式。

join_cap_styles.py
import matplotlib.pyplot as plt

# Data: Days and temperature (°C)
days = ["Mon", "Tue", "Wed", "Thu", "Fri"]
temp = [15, 17, 16, 18, 20]

# Create a line chart with styling
plt.plot(days, temp, linewidth=5, linestyle="solid", 
         joinstyle="bevel", capstyle="round", color="blue", label="Temp")

# Add labels, title, and legend
plt.xlabel("Day")
plt.ylabel("Temperature (°C)")
plt.title("Temperature (Week of March 3, 2025)")
plt.legend()

# Display the chart
plt.show()

该折线图跟踪 2025 年 3 月一周的每日温度。joinstyle="bevel" 参数设置线段的连接方式,创建斜角连接,而 capstyle="round" 则将线条的末端变为圆形。linewidth=5 使这些效果可见。

连接样式(“miter”、“round”、“bevel”)影响拐角,对于技术图中的粗线很有用。端盖样式(“butt”、“round”、“projecting”)定义线条端点,增强稀疏数据的清晰度,例如此天气趋势,其中星期五的温度峰值为 20°C。

线条样式和标记

此示例使用线条样式和标记来显示网站访问者的图表。

line_styles_markers.py
import matplotlib.pyplot as plt

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

# Create a line chart with styling
plt.plot(months, visitors, linestyle="--", marker="o", markersize=10, 
         linewidth=2, color="purple", label="Visitors")

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

# Display the chart
plt.show()

该图表显示了过去五个月的网站访问者,样式为虚线(linestyle="--")和圆形标记(marker="o")。markersize=10linewidth=2 增强了可见性,而“紫色”则添加了独特的颜色。

线条样式(如“solid”、“dashed”、“dotted”或“dashdot”)区分趋势,标记(例如,“o”、“s”、“^”)突出显示数据点。在这里,带有标记的虚线强调了每月的变化,五月份达到 90,000 的峰值,非常适合跟踪数字分析中的增长情况。

颜色和渐变

此示例将颜色和渐变应用于销售数据的条形图。

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

# Data: Products and sales (thousands $)
products = ["Laptops", "Phones", "Tablets"]
sales = [40, 60, 30]

# Create a gradient colormap
colors = plt.cm.viridis(np.linspace(0, 1, len(products)))

# Create a bar chart with gradient
bars = plt.bar(products, sales, color=colors, edgecolor="black", linewidth=1.5)

# Add labels and title
plt.xlabel("Product")
plt.ylabel("Sales (thousands $)")
plt.title("Product Sales (March 2025)")

# Display the chart
plt.show()

该条形图显示了 2025 年 3 月三种产品的销售额,样式为“viridis”渐变。plt.cm.viridis 函数生成颜色范围,并通过 color 参数应用。黑色边缘 (edgecolor="black") 和 linewidth=1.5 勾勒出条形图的轮廓。

渐变增强了视觉层次结构——在这里,手机 (60) 以更亮的色调脱颖而出。 Matplotlib 支持颜色映射,例如“plasma”、“inferno”或纯色(例如,“red”)。这种样式适合销售报告,使数据比较更加突出,同时保持专业的外观。

透明度和填充样式

此示例使用透明度和填充来显示带有区域填充的折线图。

transparency_fill.py
import matplotlib.pyplot as plt

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

# Create a line chart with fill
plt.plot(days, prices, linestyle="-", color="darkgreen", linewidth=2, label="Price")
plt.fill_between(days, prices, 145, color="green", alpha=0.3)

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

# Display the chart
plt.show()

该图表跟踪一周内的股票价格,底部填充了实线和区域。 fill_between 函数从基线 (145) 填充到价格线,使用 alpha=0.3 实现轻微的透明度。线条样式为深绿色,linewidth=2

透明度 (alpha) 可以柔化填充,显示重叠或网格线——在这里,它突出显示了 145 以上的价格涨幅。填充样式可以强调趋势,比如这只股票到星期五上涨到 160,这在细微效果很重要的金融可视化中很有用。

自定义网格和背景

此示例使用自定义网格和背景颜色来设置折线图的样式。

grid_background.py
import matplotlib.pyplot as plt

# Data: Months and energy use (GWh)
months = ["Jan", "Feb", "Mar", "Apr", "May"]
energy = [120, 130, 110, 115, 125]

# Create a line chart with styling
plt.plot(months, energy, linestyle="-.", color="orange", linewidth=3, label="Energy")

# Customize grid and background
plt.grid(color="gray", linestyle="--", linewidth=0.5, alpha=0.7)
plt.gca().set_facecolor("#f0f0f0")

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

# Display the chart
plt.show()

该图表显示了过去五个月的能源消耗,样式为橙色的点划线 (linestyle="-.")。 grid 函数添加了一个灰色的虚线网格,alpha=0.7set_facecolor 设置了一个浅灰色背景。

自定义网格有助于提高可读性——在这里,它们框定了能源下降(3 月为 110)和峰值(2 月为 130)。背景颜色(如“#f0f0f0”)增强了对比度,使该图表适用于能源报告或演示文稿,其中样式支持数据清晰度。

图表样式的最佳实践

来源

Matplotlib 绘图文档

在本文中,我们探讨了 Matplotlib 图表的样式,包括连接和端盖样式、线条样式、颜色、渐变以及自定义网格,使用基本的折线图和条形图。

作者

我叫 Jan Bodnar,是一位充满热情的程序员,拥有多年的编程经验。 我自 2007 年以来一直在撰写编程文章。到目前为止,我已经撰写了 1400 多篇文章和 8 本电子书。 我在编程教学方面拥有八年多的经验。

列出 所有 Python 教程