Matplotlib - 使用Cycler进行样式设置



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

导入Cycler - 要开始使用Cycler,您需要将其导入到Python脚本中。

from cycler import cycler

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

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

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

"color_cycle" 是一个Cycler对象,它循环遍历红色、绿色和蓝色。获得Cycler后,您可以将其链接到matplotlib的绘图属性。

循环遍历多个属性

Cycler包提供了用于组合和操作多个Cycler以创建复杂样式变化的高级操作。这意味着您可以将cycler加在一起或将它们相乘以组合不同的属性。

以下是cycler中的不同操作:

  • Cycler加法 - 使用+运算符可以组合多个Cycler对象。例如:
cycler(color=['r', 'g', 'b']) + cycler(linestyle=['-', '--', ':'])
  • Cycler乘法 - 可以将Cycler相乘以创建更广泛的独特样式。例如
cycler(color=['r', 'g', 'b']) * cycler(linestyle=['-', '--', ':'])
  • 整数乘法 - 可以将Cycler对象乘以整数值以增加其长度。cycler * 2 和 2 * cycler 都产生相同的结果,重复元素。以下是语法
color_cycle * 2
  • Cycler连接 - 可以使用Cycler.concat()方法或顶级concat()函数连接Cycler对象。

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

  • 设置默认属性循环(rc参数) - 这是全局设置,它确保每个后续绘图都将设置为指定的样式。
  • 设置单个轴对的属性循环 - 这是局部设置,它将自定义属性循环专门应用于特定的一组轴。

设置默认属性循环(rc参数)

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

示例1

这是一个基本的示例,演示了如何为多个绘图循环遍历不同的线型。此处使用plt.rc()方法设置绘图的默认线型。

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()

输出

执行上述代码后,我们将获得以下输出:

Basic Example 1

让我们通过将多个(颜色和线型)循环器加在一起(+符号)来组合它们。

示例2

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

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()

输出

执行上述代码后,我们将获得以下输出:

Styling with Cycler Example 1

设置单个轴对的属性循环

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

示例

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

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()

输出

执行上述代码后,我们将获得以下输出:

styling_with_cycler_ex2
广告

© . All rights reserved.