使用 Matplotlib 格式化货币绘图

MatplotlibMatplotlibBeginner
立即练习

This tutorial is from open-source community. Access the source code

💡 本教程由 AI 辅助翻译自英文原版。如需查看原文,您可以 切换至英文原版

简介

在可视化金融数据时,使用货币符号对坐标轴进行适当的格式化至关重要。Matplotlib 是一个用于创建可视化图表的强大 Python 库,但默认情况下,它不会在坐标轴上显示货币符号。

在这个实验中,我们将学习如何自定义 Matplotlib 绘图,以便在 y 轴标签上显示美元符号。当处理金融数据、销售数据、预算或任何其他需要货币格式化的数据集时,这项技能非常有用。

虚拟机使用提示

虚拟机启动完成后,点击左上角切换到 Notebook 标签页,即可访问 Jupyter Notebook 进行练习。

click-notebook

你可能需要等待几秒钟,让 Jupyter Notebook 加载完成。由于 Jupyter Notebook 的限制,操作验证无法实现自动化。

如果你在实验过程中遇到任何问题,随时向 Labby 寻求帮助。实验结束后请提供反馈,我们会及时为你解决任何问题。


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL matplotlib(("Matplotlib")) -.-> matplotlib/PlotCustomizationGroup(["Plot Customization"]) matplotlib(("Matplotlib")) -.-> matplotlib/BasicConceptsGroup(["Basic Concepts"]) matplotlib(("Matplotlib")) -.-> matplotlib/PlottingDataGroup(["Plotting Data"]) matplotlib/BasicConceptsGroup -.-> matplotlib/importing_matplotlib("Importing Matplotlib") matplotlib/BasicConceptsGroup -.-> matplotlib/saving_figures("Saving Figures to File") matplotlib/PlottingDataGroup -.-> matplotlib/line_plots("Line Plots") matplotlib/PlotCustomizationGroup -.-> matplotlib/titles_labels("Adding Titles and Labels") matplotlib/PlotCustomizationGroup -.-> matplotlib/axis_ticks("Axis Ticks Customization") matplotlib/PlotCustomizationGroup -.-> matplotlib/grid_config("Grid Configuration") matplotlib/PlotCustomizationGroup -.-> matplotlib/text_annotations("Text Annotations") subgraph Lab Skills matplotlib/importing_matplotlib -.-> lab-48691{{"使用 Matplotlib 格式化货币绘图"}} matplotlib/saving_figures -.-> lab-48691{{"使用 Matplotlib 格式化货币绘图"}} matplotlib/line_plots -.-> lab-48691{{"使用 Matplotlib 格式化货币绘图"}} matplotlib/titles_labels -.-> lab-48691{{"使用 Matplotlib 格式化货币绘图"}} matplotlib/axis_ticks -.-> lab-48691{{"使用 Matplotlib 格式化货币绘图"}} matplotlib/grid_config -.-> lab-48691{{"使用 Matplotlib 格式化货币绘图"}} matplotlib/text_annotations -.-> lab-48691{{"使用 Matplotlib 格式化货币绘图"}} end

安装库并创建示例数据

在第一步中,我们将导入必要的库,并为绘图创建示例金融数据。我们需要导入用于可视化的 Matplotlib 和用于数据生成的 NumPy。

在你的 Notebook 的第一个单元格中,输入并运行以下代码以导入所需的库:

## Import necessary libraries
import matplotlib.pyplot as plt
import numpy as np

## Display plots inline in the notebook
%matplotlib inline

print("Libraries imported successfully!")

运行代码后(按 Shift + Enter),你应该会看到输出:

Libraries imported successfully!
libraries-imported

现在,让我们创建一些用于可视化的示例金融数据。金融数据通常表示随时间变化的值,因此我们将创建一个简单的数据集,它可能代表一段时间内的每日收入。

在一个新的单元格中,添加并运行以下代码:

## Set a random seed for reproducibility
np.random.seed(42)

## Generate financial data: 30 days of revenue data
days = np.arange(1, 31)
daily_revenue = np.random.uniform(low=1000, high=5000, size=30)

print("Sample of daily revenue data (first 5 days):")
for i in range(5):
    print(f"Day {days[i]}: ${daily_revenue[i]:.2f}")

运行此代码后,你将看到示例收入数据的前 5 天:

Sample of daily revenue data (first 5 days):
Day 1: $3745.40
Day 2: $3992.60
Day 3: $2827.45
Day 4: $4137.54
Day 5: $1579.63

这个示例数据代表了 30 天内每日收入在 1000 美元到 5000 美元之间的值。我们将在下一步中使用这些数据来创建我们的绘图。

创建基本的金融绘图

现在我们已经准备好了数据,让我们创建一个基本的绘图来可视化每日收入。我们将从一个简单的折线图开始,展示这 30 天内的收入趋势。

在你的 Notebook 的新单元格中,添加并运行以下代码:

## Create a figure and axes
fig, ax = plt.subplots(figsize=(10, 6))

## Plot the daily revenue data
ax.plot(days, daily_revenue, marker='o', linestyle='-', color='blue', linewidth=2, markersize=6)

## Add labels and title
ax.set_xlabel('Day', fontsize=12)
ax.set_ylabel('Revenue', fontsize=12)
ax.set_title('Daily Revenue Over 30 Days', fontsize=14, fontweight='bold')

## Add grid for better readability
ax.grid(True, linestyle='--', alpha=0.7)

## Display the plot
plt.tight_layout()
plt.show()

print("Basic plot created successfully!")

运行此代码后,你应该会看到一个显示每日收入趋势的折线图。它应该类似于下面这样(由于随机生成,实际值可能会略有不同):

Basic Revenue Plot

让我们来详细分析一下这段代码的操作:

  1. fig, ax = plt.subplots(figsize=(10, 6)) — 创建了一个大小为 10×6 英寸的图形和坐标轴
  2. ax.plot(days, daily_revenue, ...) — 绘制数据,x 轴为天数,y 轴为收入
  3. ax.set_xlabel()ax.set_ylabel()ax.set_title() — 为绘图添加标签和标题
  4. ax.grid() — 添加网格,使数据更易于读取
  5. plt.tight_layout() — 调整边距,确保所有内容布局合理
  6. plt.show() — 显示绘图

注意,目前 y 轴显示的是普通数字,没有美元符号。在下一步中,我们将修改绘图,使 y 轴显示正确的货币格式。

用美元符号格式化 y 轴标签

现在我们已经有了基本的绘图,接下来让我们对 y 轴标签进行格式化,使其显示美元符号。这将使我们的金融数据更易读,呈现效果也更专业。

为了格式化 y 轴上的刻度标签,我们将使用 Matplotlib 的 ticker 模块,该模块提供了各种格式化选项。具体来说,我们将使用 StrMethodFormatter 类为 y 轴创建一个自定义格式化器。

在你的 Notebook 的新单元格中,添加并运行以下代码:

## Import the necessary module for formatting
import matplotlib.ticker as ticker

## Create a figure and axes
fig, ax = plt.subplots(figsize=(10, 6))

## Plot the daily revenue data
ax.plot(days, daily_revenue, marker='o', linestyle='-', color='blue', linewidth=2, markersize=6)

## Format y-axis with dollar signs
formatter = ticker.StrMethodFormatter('${x:,.2f}')
ax.yaxis.set_major_formatter(formatter)

## Add labels and title
ax.set_xlabel('Day', fontsize=12)
ax.set_ylabel('Revenue ($)', fontsize=12)
ax.set_title('Daily Revenue Over 30 Days', fontsize=14, fontweight='bold')

## Add grid for better readability
ax.grid(True, linestyle='--', alpha=0.7)

## Display the plot
plt.tight_layout()
plt.show()

print("Plot with dollar-formatted y-axis created!")

运行此代码后,你应该会看到一个新的绘图,其 y 轴标签带有美元符号。

让我们解释一下这段代码的关键部分:

formatter = ticker.StrMethodFormatter('${x:,.2f}')
ax.yaxis.set_major_formatter(formatter)

这个格式化字符串的作用如下:

  • $ — 在每个标签的开头添加一个美元符号
  • {x:,.2f} — 对数字进行如下格式化:
    • , — 使用逗号作为千位分隔符(例如,1,000 而不是 1000)
    • .2f — 保留两位小数(例如,$1,234.56)

这个格式化器适用于 y 轴上的所有主要刻度标签。注意,现在绘图清晰地表明这些值是以美元为单位的,这使得它更适合用于金融数据可视化。

优化绘图以实现更好的金融数据可视化

既然我们已经完成了基本的货币格式设置,接下来让我们进一步优化绘图,使其更有助于金融数据分析。我们将进行以下几方面的改进:

  1. 添加一条水平线,显示平均每日收入
  2. 添加注释,突出显示收入最高和最低的日期
  3. 自定义刻度参数,提高可读性
  4. 使用更具描述性的标题和图例

在你的 Notebook 的新单元格中,添加并运行以下代码:

## Import the necessary module for formatting
import matplotlib.ticker as ticker

## Create a figure and axes
fig, ax = plt.subplots(figsize=(12, 7))

## Plot the daily revenue data
ax.plot(days, daily_revenue, marker='o', linestyle='-', color='blue',
        linewidth=2, markersize=6, label='Daily Revenue')

## Calculate statistics
avg_revenue = np.mean(daily_revenue)
max_revenue = np.max(daily_revenue)
min_revenue = np.min(daily_revenue)
max_day = days[np.argmax(daily_revenue)]
min_day = days[np.argmin(daily_revenue)]

## Add a horizontal line for average revenue
ax.axhline(y=avg_revenue, color='r', linestyle='--', alpha=0.7,
           label=f'Average Revenue: ${avg_revenue:.2f}')

## Format y-axis with dollar signs
formatter = ticker.StrMethodFormatter('${x:,.2f}')
ax.yaxis.set_major_formatter(formatter)

## Customize tick parameters
ax.tick_params(axis='both', which='major', labelsize=10)
ax.yaxis.set_major_locator(ticker.MaxNLocator(nbins=10))
ax.xaxis.set_major_locator(ticker.MultipleLocator(base=5))

## Add annotations for max and min revenue
ax.annotate(f'Max: ${max_revenue:.2f}', xy=(max_day, max_revenue),
            xytext=(max_day+1, max_revenue+200),
            arrowprops=dict(facecolor='black', shrink=0.05, width=1.5))

ax.annotate(f'Min: ${min_revenue:.2f}', xy=(min_day, min_revenue),
            xytext=(min_day+1, min_revenue-200),
            arrowprops=dict(facecolor='black', shrink=0.05, width=1.5))

## Add labels and title
ax.set_xlabel('Day of Month', fontsize=12)
ax.set_ylabel('Revenue ($)', fontsize=12)
ax.set_title('Daily Revenue Analysis - 30 Day Period', fontsize=14, fontweight='bold')

## Set x-axis limits to show a bit of padding
ax.set_xlim(0, 31)

## Add grid for better readability
ax.grid(True, linestyle='--', alpha=0.7)

## Add legend
ax.legend(loc='upper right', fontsize=10)

## Display the plot
plt.tight_layout()
plt.show()

print("Enhanced financial plot created successfully!")

运行此代码后,你将看到一个信息更加丰富的绘图,具备以下特点:

  1. y 轴采用美元符号格式化
  2. 有一条红色虚线水平线,显示平均收入
  3. 有注释指向收入最高和最低的日期
  4. 刻度标记更清晰,间距更合理
  5. 有一个图例,说明每个元素的含义

让我们解释一下其中一些新元素:

  • ax.axhline() — 在指定的 y 值处添加一条水平线(在本例中为平均收入)
  • ax.yaxis.set_major_locator() — 控制 y 轴上显示的刻度标记数量
  • ax.xaxis.set_major_locator() — 设置 x 轴以 5 天为间隔显示刻度
  • ax.annotate() — 添加带有箭头的文本注释,指向特定的数据点
  • ax.legend() — 添加一个图例,解释绘图上的不同元素

这些改进通过突出关键统计数据并使数据更易于解读,让绘图在金融分析中更具实用性。

保存绘图并创建可复用函数

在这最后一步,我们将创建一个可复用的函数来生成带有货币格式的绘图,并将可视化结果保存到文件中。这种方法能让你在未来轻松地将相同的格式应用到不同的金融数据集上。

在你的 Notebook 的新单元格中,添加并运行以下代码:

def create_currency_plot(x_data, y_data, title='Financial Data',
                         xlabel='X-Axis', ylabel='Amount ($)',
                         filename=None, show_stats=True):
    """
    Create a plot with currency formatting on the y-axis.

    Parameters:
    -----------
    x_data : array-like
        Data for the x-axis
    y_data : array-like
        Data for the y-axis (currency values)
    title : str
        Title of the plot
    xlabel : str
        Label for the x-axis
    ylabel : str
        Label for the y-axis
    filename : str, optional
        If provided, save the plot to this filename
    show_stats : bool
        Whether to show statistics (average, min, max)

    Returns:
    --------
    fig, ax : tuple
        The figure and axes objects
    """
    ## Import the necessary module for formatting
    import matplotlib.ticker as ticker

    ## Create a figure and axes
    fig, ax = plt.subplots(figsize=(12, 7))

    ## Plot the data
    ax.plot(x_data, y_data, marker='o', linestyle='-', color='blue',
            linewidth=2, markersize=6, label='Data')

    if show_stats:
        ## Calculate statistics
        avg_value = np.mean(y_data)
        max_value = np.max(y_data)
        min_value = np.min(y_data)
        max_x = x_data[np.argmax(y_data)]
        min_x = x_data[np.argmin(y_data)]

        ## Add a horizontal line for average value
        ax.axhline(y=avg_value, color='r', linestyle='--', alpha=0.7,
                   label=f'Average: ${avg_value:.2f}')

        ## Add annotations for max and min values
        ax.annotate(f'Max: ${max_value:.2f}', xy=(max_x, max_value),
                    xytext=(max_x+1, max_value+200),
                    arrowprops=dict(facecolor='black', shrink=0.05, width=1.5))

        ax.annotate(f'Min: ${min_value:.2f}', xy=(min_x, min_value),
                    xytext=(min_x+1, min_value-200),
                    arrowprops=dict(facecolor='black', shrink=0.05, width=1.5))

    ## Format y-axis with dollar signs
    formatter = ticker.StrMethodFormatter('${x:,.2f}')
    ax.yaxis.set_major_formatter(formatter)

    ## Customize tick parameters
    ax.tick_params(axis='both', which='major', labelsize=10)

    ## Add labels and title
    ax.set_xlabel(xlabel, fontsize=12)
    ax.set_ylabel(ylabel, fontsize=12)
    ax.set_title(title, fontsize=14, fontweight='bold')

    ## Add grid for better readability
    ax.grid(True, linestyle='--', alpha=0.7)

    ## Add legend
    if show_stats:
        ax.legend(loc='best', fontsize=10)

    ## Adjust layout
    plt.tight_layout()

    ## Save the plot if filename is provided
    if filename:
        plt.savefig(filename, dpi=300, bbox_inches='tight')
        print(f"Plot saved as '{filename}'")

    return fig, ax

## Use our function to create and save a plot
fig, ax = create_currency_plot(
    days,
    daily_revenue,
    title='Monthly Revenue Report',
    xlabel='Day of Month',
    ylabel='Daily Revenue ($)',
    filename='revenue_plot.png'
)

## Display the plot
plt.show()

print("Function created and plot saved successfully!")

运行此代码后,你将看到:

  1. 一个与我们上一步创建的绘图类似的图表,但这次是使用我们自定义的函数生成的
  2. 一条确认消息,表明绘图已保存到名为 revenue_plot.png 的文件中

我们创建的函数:

  • 接受 x 轴和 y 轴的数据
  • 允许自定义标签和标题
  • 有一个选项可以将绘图保存到文件中
  • 可以显示或隐藏诸如平均值、最小值和最大值等统计信息
  • 返回图形和坐标轴对象,以便在需要时进行进一步的自定义

这个可复用的函数让你在未来能够轻松创建格式一致的金融绘图。你只需使用不同的数据集调用这个函数,它就会自动处理所有的货币格式设置和统计注释。

为了验证我们的绘图是否正确保存,让我们检查文件是否存在:

import os
if os.path.exists('revenue_plot.png'):
    print("Plot file exists! Size:", os.path.getsize('revenue_plot.png'), "bytes")
else:
    print("Plot file was not saved correctly.")

你应该会看到一条消息,确认文件存在并显示其大小。

恭喜你!你已经成功学会了如何使用美元符号格式化绘图,并使用 Matplotlib 创建专业的金融可视化图表。

总结

在本次实验中,我们学习了如何使用 Matplotlib 创建具有正确货币格式的金融绘图。我们涵盖了几个重要的概念:

  1. 生成并处理示例金融数据
  2. 使用 Matplotlib 创建基本绘图
  3. 使用 StrMethodFormatter 类为 y 轴标签添加美元符号格式
  4. 通过统计信息、注释和改进的样式来优化绘图
  5. 创建一个可复用的函数,用于生成格式一致的货币绘图

这些技能对于任何从事金融数据可视化工作的人来说都是必不可少的,因为它们能让你创建专业且信息丰富的图表,清晰地传达货币价值。

你所学的技术可以应用于各种金融数据集,例如:

  • 销售和收入报告
  • 预算分析
  • 投资绩效跟踪
  • 成本分析
  • 费用跟踪

通过使用货币符号正确格式化坐标轴,你可以让可视化结果更直观、更专业,从而提高数据传达的效果。