Matplotlib 简明教程

Matplotlib - Formatting Axes

What is Formatting Axes?

Matplotlib 中轴的格式设置包括定制图片轴的各个方面,例如刻度、标签、刻度以及限制等。此定制增强了数据可视化的可读性和展示性。

Formatting axes in Matplotlib involves customizing various aspects of the plot’s axes such as ticks, labels, scale, limits and more. This customization enhances the readability and presentation of the data visualization.

Matplotlib 中轴的格式设置使我们能够根据数据的特征和显示要求定制可视化效果。尝试使用各个格式设置选项以创建清晰直观图片。

Formatting the axes in Matplotlib allows us to tailor the visualization according to our data’s characteristics and presentation requirements. Experiment with various formatting options to create clear and informative plots.

Use Cases

以下是格式设置轴的用例。

The following are the use cases of Formatting Axes.

  1. Enhancing Readability − Adjust font sizes, colors and labels for better visualization.

  2. Data Emphasis − Set limits and scale to focus on specific data ranges.

  3. Aesthetics − Customize appearance with titles, grid lines and spine properties.

  4. Clarity and Context − Label axes and add titles for understanding the plot’s content.

Axes Formatting Options

我们有不同的轴格式设置选项,让我们逐一详细了解。

We have different Axes formatting options let’s go through each and everyone in detail.

Ticks and Tick Labels

在 Matplotlib 中,刻度是轴上指示特定数据点的小标记,而刻度标签是对应于该刻度的值。我们可以使用 Matplotlib 中的各种函数定制其外观。

In Matplotlib ticks are the small marks on an axis that denote specific data points and where as tick labels are the values corresponding to those ticks. We can customize their appearance using various functions in Matplotlib.

若要修改刻度和刻度标签,我们可以使用 plt.xticks() 和 plt.yticks() 等方法设置其位置和标签。plt.xticks() 和 plt.yticks() 允许我们分别设置 x 轴和 y 轴上刻度的位置和标签。我们可以使用 plt.tick_params() 调整刻度的外观,以修改大小、颜色、方向等方面。

To modify ticks and tick labels we can use methods like plt.xticks() and plt.yticks() to set their positions and labels. plt.xticks() and plt.yticks() allow us to set the locations and labels of ticks on the x and y axes respectively. We can adjust the appearance of ticks using plt.tick_params() to change aspects like size, color, direction etc.

可以通过 plt.gca().xaxis 或 plt.gca().yaxis 以及 set_major_formatter() 等方法,对刻度标签进行格式设置,以控制它们的显示方式,例如科学记数法、小数位数、日期格式等。

Formatting the tick labels can be done through plt.gca().xaxis or plt.gca().yaxis with methods like set_major_formatter() to control their display such as scientific notation, decimal places, date format and etc.

此外,为了更精细的控制,我们可以使用 ax.get_xticks()、ax.get_yticks()、ax.get_xticklabels() 和 ax.get_yticklabels() 来访问特定的刻度和标签,然后分别修改它们。

Additionally for more granular control we can access specific ticks and labels using ax.get_xticks(), ax.get_yticks(), ax.get_xticklabels(), ax.get_yticklabels() and then modify them individually.

Example

在这个示例中,我们使用 Matplotlib 库中讨论过的函数和方法,设置了带有刻度和刻度标签的绘图。

In this example we are setting the ticks and tick labels of a plot with the use of above discussed functions and methods available in matplotlib library.

import matplotlib.pyplot as plt
import numpy as np

# Generating sample data
x = np.linspace(0, 10, 100)
y = np.sin(x)

# Creating a plot
plt.figure(figsize=(8, 5))
plt.plot(x, y)

# Customizing ticks and tick labels
plt.xticks(np.arange(0, 11, 2))  # Set x-axis ticks at intervals of 2
plt.yticks(fontsize=10, color='red')  # Customize y-axis tick labels (font size and color)
plt.xlabel('X-axis', fontsize=12)
plt.ylabel('Y-axis', fontsize=12)
plt.title('Ticks and Tick Labels Formatting', fontsize=14)
plt.show()

执行上述代码,我们将得到以下输出 −

On executing the above code we will get the following output −

ticks ticklabels

Axis Limits and Scale

在创建可视化时,轴限制和比例是基本方面。它们控制沿着绘图或图表轴显示的数据范围和外观。

Axis limits and scale are fundamental aspects when creating visualizations. They control the range and appearance of the data displayed along the axes of a plot or chart.

Axis Limits

轴限制定义在每个轴上显示的值跨度。通过设置限制,我们可以通过强调特定细节或趋势来关注特定的数据范围。例如,在一个散点图中,如果我们设置轴限制,那么它可以放大特定的感兴趣区域。

The Axis limits define the span of values shown on each axis. By setting limits we can focus on a specific range of data by emphasizing particular details or trends. For example in a scatter plot if we set axis limits then it can zoom in on a particular region of interest.

Scale

比例确定数据如何沿着轴分布和表示。常见的比例包括线性、对数和分类。线性比例表示沿轴均匀分布的数据,而对数比例强调数量级的变化,分类比例用于非数字数据或类别。

The scale determines how the data is distributed and represented along an axis. Common scales include linear, logarithmic and categorical. Linear scale represents data equally spaced along the axis where as logarithmic scale emphasizes changes in orders of magnitude and categorical scale is used for non-numeric data or categories.

以下是与轴限制和比例相关的主要考虑因素和措施。

Here are key considerations and actions related to axis limits and scale.

  1. Setting Limits − Define the minimum and maximum values for each axis to control what portion of the data is displayed.

  2. Zooming In/Out − Adjust axis limits to focus on specific data ranges or zoom out to show the overall context.

  3. Scale Transformation − Changing the scale type can alter how the data is perceived. For instance by using a logarithmic scale can better visualize exponential growth or wide-ranging data.

  4. Normalization − Normalize data if needed to bring different scales into a comparable range especially when plotting multiple datasets on the same graph.

  5. Limiting Outliers − Set axis limits to exclude outliers or anomalies by providing a clearer view of the main data distribution.

  6. Scale Customization − Some visualization libraries allow customization of scale aesthetics such as tick placement and labeling for different scales.

在 Python 库(如 Matplotlib 或 Seaborn)中提供了操作轴限制和比例的功能,允许用户详细控制数据在绘图中的显示方式。

In Python libraries like Matplotlib or Seaborn provide functionalities to manipulate axis limits and scales by allowing user for detailed control over how data is presented in plots.

Example

以下是一个使用 Python 的 Matplotlib 库的示例,演示了如何设置轴限制和更改比例。

Here’s an example using Python’s Matplotlib library to demonstrate setting axis limits and changing scales.

import matplotlib.pyplot as plt
import numpy as np

# Generating data
x = np.linspace(0.1, 100, 500)
y = np.sin(x)

# Creating a figure and axes object
fig, axs = plt.subplots(1, 2, figsize=(12, 5))

# Plot with default linear scale
axs[0].plot(x, y)
axs[0].set_title('Linear Scale')

# Plot with logarithmic scale for the y-axis
axs[1].plot(x, y)
axs[1].set_yscale('log')  # Set logarithmic scale for the y-axis
axs[1].set_title('Logarithmic Scale (y-axis)')
plt.tight_layout()
plt.show()

执行上述代码,我们将得到以下输出 −

On executing the above code we will get the following output −

axislimits scale

Axis Labels and Titles

轴标签和标题是任何可视化中提供关于绘图上所表示数据的背景和信息的重要组成部分。它们帮助读者理解每个轴代表什么以及可视化的总体目的。

Axis labels and titles are crucial components of any visualization in providing context and information about the data represented on the plot. They help readers understand what each axis represents and the overall purpose of the visualization.

自定义轴标签和标题涉及指定文本、调整字体大小、设置字体粗细、更改颜色以及在绘图中适当放置它们以确保清晰度和可读性。

Customizing axis labels and titles involves specifying text, adjusting font size, setting font weight, changing color and positioning them appropriately within the plot to ensure clarity and readability.

Axis Labels

轴标签描述沿着每个轴显示的数据的数量或性质。例如,在一个散点图中,y 轴上为身高,x 轴上为体重,标签可能是 "Height (cm)""Weight (kg)" 。它们明确了已绘图值的含义。

The Axis labels describe the quantity or nature of the data displayed along each axis. For example in a scatter plot with height on the y-axis and weight on the x-axis, the labels might be "Height (cm)" and "Weight (kg)". They make it clear what the plotted values signify.

Titles

一个标题为整个绘图提供了一个总括性的描述或背景。它简要解释了可视化的内容、它可能说明了什么关系或模式,或者可以从中得出什么见解。

A title provides an overarching description or context for the entire plot. It gives a brief explanation of what the visualization is about, what relationships or patterns it might illustrate or what insights can be drawn from it.

Example

以下是使用 Python 的 Matplotlib 库创建具有标记轴和标题的简单绘图的示例。

The following is an example using Python’s Matplotlib library to create a simple plot with labeled axes and a title.

import matplotlib.pyplot as plt
import numpy as np

# Generating data
x = np.linspace(0, 10, 100)
y = np.cos(x)

# Creating the plot
plt.plot(x, y)

# Adding axis labels and title
plt.xlabel('X-axis Label')
plt.ylabel('Y-axis Label')
plt.title('Cosine Wave Plot')
plt.show()

执行上述代码,我们将得到以下输出 −

On executing the above code we will get the following output −

axis labels title

Grid Lines and Spines

网格线和轴线是有助于通过提供参考点和描绘绘图区域来理解和解释绘图的可视化组件。

Grid lines and spines are visual components that aid in understanding and interpreting plots by providing reference points and delineating the plot area.

自定义网格线和轴线允许通过提高其清晰度和视觉吸引力来更好地展示和强调绘图的某些方面。我们可以调整网格线和轴线的视觉外观、可见性和属性以满足可视化要求。

Customizing grid lines and spines allows for better presentation and emphasis on certain aspects of the plot by enhancing its clarity and visual appeal. We can adjust the appearance, visibility and properties of grid lines and spines to suit the visualization’s requirements.

Grid Lines

这些是跨越绘图区域的水平线和垂直线,在沿着轴的刻度处相交。它们有助于在绘图中直观地估计数据点和关系。网格线可以存在于一个轴或两个轴上,它们可以在样式、颜色和可见度方面进行自定义。

These are horizontal and vertical lines that span the plot area, intersecting at the ticks along the axes. They help in visually estimating data points and relationships within the plot. Grid lines can be present along one or both axes and they can be customized in terms of style, color and visibility.

Spines

轴线是形成图框边界的线。它们连接轴刻度并定义数据区域的边界。轴线可以针对绘图的每个侧面(例如顶部、底部、左侧、右侧)进行单独自定义,从而允许改变它们的视觉外观、厚度和位置。

Spines are the lines that form the boundaries of the plot box. They connect the axis tick marks and define the boundaries of the data area. Spines can be customized individually for each side of the plot such as top, bottom, left, right which allows changes in their appearance, thickness and position.

在 Matplotlib 中,我们可以使用各种方法和属性来控制网格线和轴线。

In Matplotlib we can control grid lines and spines using various methods and attributes.

Example

下面是使用 plt.grid() 和 plt.gca().spines 方法设置绘图的网格线和轴线的示例。

Here is the example of setting the gridlines and spines of a plot by using the plt.grid() and plt.gca().spines methods.

import matplotlib.pyplot as plt

# Generating data
x = [1, 2, 3, 4, 5]
y = [2, 4, 6, 8, 10]

# Creating a plot
plt.plot(x, y)

# Displaying grid lines
plt.grid(True)  # Show grid lines

# Customizing spines
plt.gca().spines['top'].set_linestyle('--')  # Customize top spine style
plt.gca().spines['right'].set_visible(False)  # Hide right spine
plt.show()

执行上述代码,我们将得到以下输出 −

On executing the above code we will get the following output −

grids spines

轴脊线是连接轴刻度的分界绘图区域边界的线。轴对象具有位于顶部、底部、左侧和右侧的脊线。

Axis spines are the lines connecting axis tick marks demarcating boundaries of plot area. The axes object has spines located at top, bottom, left and right.

可以通过指定颜色和宽度来绘制每个脊线。如果颜色设置为无,则任何边都不可见。

Each spine can be formatted by specifying color and width. Any edge can be made invisible if its color is set to none.

Example

import matplotlib.pyplot as plt
fig = plt.figure()
ax = fig.add_axes([0,0,1,1])
ax.spines['bottom'].set_color('blue')
ax.spines['left'].set_color('red')
ax.spines['left'].set_linewidth(2)
ax.spines['right'].set_color(None)
ax.spines['top'].set_color(None)
ax.plot([1,2,3,4,5])
plt.show()

执行上述代码,我们将得到以下输出 −

On executing the above code we will get the following output −

axis spines

Example

下面是使用 Python 的 Matplotlib 库对 x 轴和 y 轴进行标记的示例代码。

Here’s an example code for Labeling x, y-Axis in Python’s Matplotlib library.

# importing matplotlib module
import matplotlib.pyplot as plt
import numpy as np

# x-axis & y-axis values
x = [1, 2, 3, 4, 5]
y = [10, 5, 15, 20, 25]

# create a figure and axes
fig, ax = plt.subplots()

# setting title to graph
ax.set_title('Tutorials Point')

# label x-axis and y-axis
ax.set_ylabel('y-AXIS')
ax.set_xlabel('x-AXIS')

# function to plot and show graph
ax.plot(x, y)
plt.show()

执行上述代码,我们将得到以下输出 −

On executing the above code we will get the following output −

xylabel

Example

在 Python matplotlib 中设置轴,限制 x 轴和 y 轴,在本例中为 (10,0) 和 (0,40)。轴的限制设置了グラフ中应涵盖的最高绘图。默认情况下,将指出 x 轴的最大值和给定点的 y 轴的最大值。

Formatting Axes in Python-matplotlib- Limits of x, y-axis which in this case is, (10,0) and (0,40) respectively. Limits of axes set the highest plots to be covered in the graph. By default the max value of x-axis and max value of y-axis of the given points will be pointed.

import matplotlib.pyplot as plt
import numpy as np

x = [1, 2, 3, 4, 5]
y = [10, 5, 15, 20, 25]

# create a figure and axes
fig, ax = plt.subplots()

ax.set_title('Tutorials Point')

ax.set_ylabel('y-AXIS')
ax.set_xlabel('x-AXIS')

# sets x, y-axis limits on the graph
ax.set_xlim(0, 10)
ax.set_ylim(0, 40)

# function to plot and show graph
ax.plot(x, y)
plt.show()

执行上述代码,我们将得到以下输出 −

On executing the above code we will get the following output −

xylimits