Matplotlib 简明教程
Matplotlib - Autoscaling
What is Autoscaling?
Matplotlib 中的自动调整是指基于正在绘制的数据自动调整轴限制,确保绘制的数据适合于该图表的可见区域,而不会被剪切掉或超出图表界限。此功能旨在通过动态调整轴限制以容纳整个数据集来提供数据的最佳视图。
Autoscaling in Matplotlib refers to the automatic adjustment of axis limits based on the data being plotted, ensuring that the plotted data fits within the visible area of the plot without getting clipped or extending beyond the plot boundaries. This feature aims to provide an optimal view of the data by dynamically adjusting the axis limits to accommodate the entire dataset.
Key Aspects of Autoscaling in Matplotlib
以下是 Matplotlib 库中自动调整的关键方面。
The below are the key aspects of Autoscaling in Matplotlib library.
Automatic Adjustment
在 Matplotlib 中,自动调整或自动缩放是指该库基于所绘制的数据动态地确定和设置 x 轴和 y 轴的轴限制的过程。其目的是确保整个数据集在图表中可见,而无需任何数据点被剪切掉或超出图表界限。
In Matplotlib automatic adjustment or autoscaling refers to the process by which the library dynamically determines and sets the axis limits both x-axis and y-axis based on the data being plotted. The aim is to ensure that the entire dataset is visible within the plot without any data points being clipped or extending beyond the plot boundaries.
自动调整的关键方面如下。
The key aspects of automatic adjustment are as follows.
Data-Based Limits − Matplotlib 检查所绘制数据的范围以确定两个轴的合适的最小和最大限制。
Data-Based Limits − Matplotlib examines the range of the data being plotted to determine suitable minimum and maximum limits for both axes.
Data Visibility − 目的是在图表区域内清晰地显示所有数据点,优化视图以进行可视化。
Data Visibility − The goal is to display all data points clearly within the plot area, optimizing the view for visualization.
Dynamic Updates − 当创建或修改图表时,Matplotlib 重新计算和调整轴限制,以适应整个数据范围。
Dynamic Updates − When the plot is created or modified, Matplotlib recalculates and adjusts the axis limits as needed to accommodate the entire data range.
Preventing Clipping − 自动缩放确保因图表界限而不会剪切或隐藏任何数据点。
Preventing Clipping − Autoscaling ensures, that no data points are clipped or hidden due to the plot boundaries.
Manual Override − 用户还可以使用 plt.axis('auto') 或 plt.axis('tight') 等命令显式启用自动缩放,让 Matplotlib 根据所绘制的数据动态地调整轴限制。
Manual Override − Users can also explicitly enable autoscaling using commands like plt.axis('auto') or plt.axis('tight') to let Matplotlib dynamically adjust the axis limits.
在此示例中,plt.axis('auto') 或 plt.axis('tight') 通过允许 Matplotlib 根据所绘制的数据动态调整轴限制来启用自动缩放。该库重新计算限制以确保所有数据点在图表区域内可见,从而提供数据的最佳视图。
In this example plt.axis('auto') or plt.axis('tight') enables autoscaling by allowing Matplotlib to dynamically adjust the axis limits based on the data being plotted. The library recalculates the limits to ensure that all data points are visible within the plot area by providing an optimal view of the data.
import matplotlib.pyplot as plt
# Sample data
x = [1, 2, 3, 4, 5]
y = [2, 4, 6, 8, 10]
# Creating a plot with autoscaling
plt.plot(x, y, marker='o')
# Automatically adjust axis limits
plt.axis('auto') # or simply plt.axis('tight') for tight axis limits
plt.xlabel('X-axis')
plt.ylabel('Y-axis')
plt.title('Plot with Autoscaling')
plt.show()
以下是上面代码的输出: -
Following is the output of the above code −
Tight Layout
在 Matplotlib 中, tight_layout() 是一个函数,可自动调整子图参数,以确保轴标签、标题和其他适应图示区域的项目元素不会重叠或被切断。此函数通过调整子图和其他图表元素之间的间距来优化布局。
In Matplotlib tight_layout() is a function that automatically adjusts the subplot parameters to ensure that the plot elements such as axis labels, titles and other items which fit within the figure area without overlapping or getting cut off. This function optimizes the layout by adjusting the spacing between subplots and other plot elements.
以下是紧密布局的主要方面:
The below are the key Aspects of tight_layout:
Optimizing Layout − tight_layout() 函数优化了图中的子图和图表元素的排列,以最大限度地减少重叠并最大化空间利用率。
Optimizing Layout − tight_layout() function optimizes the arrangement of subplots and plot elements within a figure to minimize overlaps and maximize space utilization.
Preventing Overlapping Elements − 它调整了子图、轴、标签和标题之间的填充和间距,以防止图表元素重叠或剪切掉。
Preventing Overlapping Elements − It adjusts the padding and spacing between subplots, axes, labels and titles to prevent any overlapping or clipping of plot elements.
Automatic Adjustment − 此函数在创建复杂的多子图图形或处理各种图表元素时特别有用。
Automatic Adjustment − This function is particularly useful when creating complex multi-subplot figures or when dealing with various plot elements.
在此示例中,我们通过确保所有元素(如标题、标签等)正确地间隔并适应图示区域来自动调整子图的布局。
In this example we are automatically adjusting the layout of the subplots by ensuring that all elements such as titles, labels etc are properly spaced and fit within the figure area.
import matplotlib.pyplot as plt
# Creating subplots
fig, axes = plt.subplots(2, 2)
# Plotting in subplots
for i, ax in enumerate(axes.flatten()):
ax.plot([i, i+1, i+2], [i, i+1, i+2])
ax.set_title(f'Subplot {i+1}')
# Applying tight layout
plt.tight_layout()
plt.show()
以下是上面代码的输出: -
Following is the output of the above code −
plt.axis('auto')
此命令允许我们为特定轴显式启用自动缩放。
This command allows us to explicitly enable autoscaling for a specific axis.
以下是 plt.axis('auto') 的典型用法,
Here’s how plt.axis('auto') is typically used,
import matplotlib.pyplot as plt
# Creating a subplot
fig, ax = plt.subplots()
# Plotting data
ax.plot([1, 2, 3], [2, 4, 3])
plt.axis('auto')
plt.xlabel('X-axis')
plt.ylabel('Y-axis')
plt.title('Plot with Autoscaling')
plt.show()
以下是上面代码的输出: -
Following is the output of the above code −
plt.axis('tight')
在 matplotlib 中, plt.axis('tight') 是用于设置绘图的轴限,使其紧密贴合所绘数据的范围的命令。此命令调整轴限以完全包含所提供数据的最小和最大值,方法是删除数据点与绘图边缘之间的任何多余空间。
In Matplotlib plt.axis('tight') is a command used to set the axis limits of a plot to tightly fit the range of the data being plotted. This command adjusts the axis limits to exactly encompass the minimum and maximum values of the provided data by removing any excess space between the data points and the plot edges.
import matplotlib.pyplot as plt
# Sample data
x = [1, 2, 3, 4, 5]
y = [2, 4, 6, 8, 10]
# Creating a plot with tight axis limits
plt.plot(x, y, marker='o')
# Setting axis limits tightly around the data range
plt.axis('tight')
plt.xlabel('X-axis')
plt.ylabel('Y-axis')
plt.title('Plot with Tight Axis Limits')
plt.show()
以下是上面代码的输出: -
Following is the output of the above code −
Dynamic Updates
在 matplotlib 中,动态更新是指库自动调整或更新绘图元素的能力,当数据或绘图本身发生变化时。此功能确保可视化保持最新状态并对基础数据中的变化作出响应,而无需手动干预。
In Matplotlib dynamic updates refer to the ability of the library to automatically adjust or update plot elements when changes are made to the data or the plot itself. This feature ensures that the visualization remains up-to-date and responsive to changes in the underlying data without requiring manual intervention.
Key Points about Dynamic Updates in Matplotlib
Real-Time Updates − 当新数据添加到现有绘图中或对绘图元素进行修改时,matplotlib 动态更新可视化以反映这些更改。
Real-Time Updates − When new data is added to an existing plot or modifications are made to the plot elements Matplotlib dynamically updates the visualization to reflect these changes.
Automatic Redrawing − matplotlib 在发生更改时自动重绘绘图,例如添加新的数据点、调整轴限或修改绘图属性。
Automatic Redrawing − Matplotlib automatically redraws the plot when changes occur such as adding new data points, adjusting axis limits or modifying plot properties.
Interactive Plotting − matplotlib 中的交互式功能(例如 Jupyter Notebooks 或交互式后端)允许实时操作和更新绘图,以响应用户交互。
Interactive Plotting − Interactive features in Matplotlib such as in Jupyter Notebooks or interactive backends allow for real-time manipulation and updates of plots in response to user interactions.
Efficient Rendering − matplotlib 优化渲染过程以有效地更新绘图元素,同时保持视觉准确度。
Efficient Rendering − Matplotlib optimizes the rendering process to efficiently update the plot elements while maintaining visual accuracy.
在此示例中,初始绘图显示正弦波。循环模拟动态更新,通过在每次迭代中添加新的余弦波并修改绘图标题。plt.pause(1)引入暂停以显示这些更改,但在 Jupyter Notebook 等交互式环境中没有必要。
In this example the initial plot displays a sine wave. A loop simulates dynamic updates by adding new cosine waves and modifying the plot title in each iteration. plt.pause(1) introduces a pause to demonstrate the changes but in an interactive environment such as Jupyter Notebook which wouldn’t be necessary.
import matplotlib.pyplot as plt
import numpy as np
# Initial plot with random data
x = np.linspace(0, 10, 100)
y = np.sin(x)
plt.plot(x, y)
plt.xlabel('X-axis')
plt.ylabel('Y-axis')
plt.title('Dynamic Updates Example')
# Simulating dynamic updates by modifying the plot
for _ in range(5):
# Adding new data to the plot
x_new = np.linspace(0, 10, 100)
y_new = np.cos(x_new + _)
plt.plot(x_new, y_new, linestyle='--') # Plotting new data
# Updating plot properties
plt.title(f'Dynamic Update {_+1}') # Updating the plot title
plt.pause(1) # Pause to display changes (for demonstration)
plt.show()
以下是上面代码的输出: -
Following is the output of the above code −