Matplotlib 简明教程

Matplotlib - Styling with Cycler

Cycler 是从 Matplotlib 中提取的一个单独包,它旨在控制绘图的样式属性,如颜色、标记和线形样式。此工具使您可以轻松循环使用不同的样式,以便在单个轴上绘制多条线。

Cycler is a separate package that is extracted from Matplotlib, and it is designed to control the style properties like color, marker, and linestyle of the plots. This tool allows you to easily cycle through different styles for plotting multiple lines on a single axis.

Importing the Cycler - 要开始使用 Cycler,需要将其导入您的 Python 脚本。

Importing the Cycler − To start using Cycler, you need to import it into your Python script.

from cycler import cycler

这使您可以创建和操作 Cycler 以设置绘图样式。

This enables you to create and manipulate Cyclers for styling your plots.

Creating a Cycler - cycler 函数用于创建一个新 Cycler 对象。它可以用单个位置参数、一对位置参数或关键字参数组合来调用。

Creating a Cycler − The cycler function is used to create a new Cycler object. It can be called with a single positional argument, a pair of positional arguments, or a combination of keyword arguments.

# Creating a color Cycler
color_cycle = cycler(color=['r', 'g', 'b'])

“color_cycler”是一个在红色、绿色和蓝色中循环的循环器对象。一旦你有了一个循环器,你就可以将其链接到 matplotlib 的绘图属性。

The "color_cycle" is a Cycler object that cycles through the colors red, green, and blue. Once you have a Cycler, you can link it to the matplotlib’s plot attribute.

Cycling Through Multiple Properties

Cycler 包为合并和操作多个循环器以创建复杂的样式变化提供了高级操作。这意味着你可以将循环器加在一起或将其相乘以组合不同的属性。

The Cycler package provides advanced operations for combining and manipulating multiple Cyclers to create complex style variations. It means that you can add cyclers together or multiply them to combine different properties.

以下是在循环器中不同的操作 −

Following are the different operations in cycler −

  1. Cycler Addition − Multiple Cycler objects can be combined using the + operator. For example −

cycler(color=['r', 'g', 'b']) + cycler(linestyle=['-', '--', ':'])
  1. Cycler Multiplication − Cyclers can be multiplied to create a wider range of unique styles. For example:

cycler(color=['r', 'g', 'b']) * cycler(linestyle=['-', '--', ':'])
  1. Integer Multiplication − Cycler objects can be multiplied by integer values to increase their length. Both cycler * 2 and 2 * cycler yield the same result, repeating the elements. Here is the syntax:

color_cycle * 2
  1. Cycler Concatenation − Cycler objects can be concatenated using the Cycler.concat() method or the top-level concat() function.

在本教程中,我们将会探索使用 Cycler 包来自定义 Matplotlib 中绘制样式两种不同的方法。

In this tutorial, we will explore two distinct approaches for customizing the style of plots in Matplotlib using the Cycler package.

  1. Setting Default Property Cycle (rc parameter) − This is the global setting that ensures that every subsequent plot will be set to the specified style.

  2. Setting Property Cycle for a Single Pair of Axes − This is the local setting that applies a custom property cycle exclusively to a particular set of axes.

Setting Default Property Cycle (rc parameter)

在 matplotlib 中,可以通过使用 matplotlib.pyplot.rc() 方法来为所有将来的绘图指定默认样式,这将为你的绘图和坐标轴中的线条设置默认循环器。这意味着你将来创建的每个绘图都将遵循此颜色和线型循环(除非你覆盖它)。

In matplotlib, specifying a default style for all future plots will be possible by using matplotlib.pyplot.rc() method, this will set the default cycler for lines in your plots and axes. This means every plot you make in the future will follow this color and linestyle cycle unless you override it.

Example 1

这是一个演示如何遍历多个绘图的不同线型的基本示例。这里 plt.rc() 方法用于设置绘图的默认线型。

This is a basic example that demonstrates how to cycle through different line styles for multiple plots. Here the plt.rc() method is used to set the default linestyle for the plot.

import matplotlib.pyplot as plt
from cycler import cycler

# Set the property cycle for the linestyle of lines in the axes
linestyle_cycler = cycler('linestyle', ['-', ':', '-.'])
plt.rc('axes', prop_cycle=linestyle_cycler)

# Create multiple plots using a loop
for i in range(5):
   x = range(i, i + 5)
   plt.plot(range(5), x)

# Display the plot
plt.legend(['first', 'second', 'third', 'fourth', 'fifth'], loc='upper left', fancybox=True, shadow=True)
plt.show()

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

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

styling with cycler basic ex1

让我们通过向 multiple (color and a linestyle) cyclers 中添加 (+) 符号将其组合起来。

Let’s combine multiple (color and a linestyle) cyclers together by adding (+) symbol to them.

Example 2

此示例演示了如何使用 Cycler 为绘图定义默认样式(遍历颜色和线型),这使得可以轻松地使用不同的颜色('r', 'g', 'b', 'y')和线型('-', '--', ':', '-.')可视化所有绘图。

This example demonstrates how to define a default style (cycle through both colors and linestyles) for your plots using Cycler, making it easy to visualize all plots with different colors ('r', 'g', 'b', 'y') and linestyles ('-', '--', ':', '-.').

from cycler import cycler
import matplotlib.pyplot as plt
import numpy as np

# Generate sample data
x = np.linspace(0, 2 * np.pi, 50)
offsets = np.linspace(0, 2 * np.pi, 4, endpoint=False)
yy = np.transpose([np.sin(x + phi) for phi in offsets])

# Set default prop_cycle
default_cycler = (cycler(color=['r', 'g', 'b', 'y']) +
   cycler(linestyle=['-', '--', ':', '-.']))
plt.rc('lines', linewidth=4)
plt.rc('axes', prop_cycle=default_cycler)

# Plot with the default color cycle
plt.plot(yy)
plt.title('Set Default Color Cycle')
plt.show()

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

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

styling with cycler ex1

Setting Property Cycle for a Single Pair of Axes

自定义某个图形中的特定坐标轴对的样式而不影响其他轴对。你可以使用 matplotlib.axes.Axes.set_prop_cycle() 应用此自定义循环器。这意味着只有这一组特定坐标轴上的绘图将遵循指定的颜色和线宽循环。

Customize the style for a specific pair of axes within a figure without affecting others. you use the matplotlib.axes.Axes.set_prop_cycle() to apply this custom cycler. This means that only the plots on this particular set of axes will follow the specified color and linewidth cycle.

Example

在此示例中,ax0 上的第一组绘图遵循默认颜色和线型循环。ax1 上的第二组绘图使用专为此坐标轴使用 set_prop_cycle() 方法定义的自定义颜色和线宽循环。

In this example, the first set of plots on ax0 follows the default color and linestyle cycle. The second set of plots on ax1 uses a custom color and linewidth cycle defined specifically for this axis using the set_prop_cycle() method.

from cycler import cycler
import matplotlib.pyplot as plt
import numpy as np

# Generate sample data
x = np.linspace(0, 2 * np.pi, 50)
offsets = np.linspace(0, 2 * np.pi, 4, endpoint=False)
yy = np.transpose([np.sin(x + phi) for phi in offsets])

# Define a default cycler for colors and linestyles
default_cycler = (cycler(color=['r', 'g', 'b', 'y']) +
   cycler(linestyle=['-', '--', ':', '-.']))

# Set the default linewidth for lines in all plots
plt.rc('lines', linewidth=4)

# Set the default property cycle for axes to the default cycler
plt.rc('axes', prop_cycle=default_cycler)

# Create a figure and two axes
fig, (ax0, ax1) = plt.subplots(nrows=2, figsize=(7, 8))

# Plot on the first axis using the default color cycle
ax0.plot(yy)
ax0.set_title('Default Color Cycle: rgby')

# Define a custom cycler
custom_cycler = (cycler(color=['c', 'm', 'y', 'k']) +
   cycler(lw=[1, 2, 3, 4]))

# Set the custom property cycle for the second axis
ax1.set_prop_cycle(custom_cycler)

# Plot on the second axis using the custom color and linewidth cycle
ax1.plot(yy)
ax1.set_title('Custom Color Cycle: cmyk')

# Add space between the two plots
fig.subplots_adjust(hspace=0.3)

# Show the plots
plt.show()

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

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

styling with cycler ex2