使用matplotlib.style进行多图绘制
发布时间:2023-12-31 11:01:29
matplotlib.style模块可以帮助我们在绘制图形时应用预定义的样式。
在使用matplotlib进行图形绘制之前,可以通过调用matplotlib.style.use()函数来选择预定义的样式。常见的预定义样式包括:
- "default":默认样式。
- "ggplot":模仿ggplot2包的样式。
- "seaborn":模仿seaborn包的样式。
- "fivethirtyeight":模仿fivethirtyeight网站的样式。
- "bmh":默认样式的黑白版本。
以下是一个使用matplotlib.style的示例,其中包括了多图绘制的例子:
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.style as style
# 选择预定义样式
style.use('ggplot')
# 创建数据
x = np.linspace(0, 2 * np.pi, 100)
y1 = np.sin(x)
y2 = np.cos(x)
# 绘制 个子图
plt.subplot(2, 1, 1)
plt.plot(x, y1, label='sin(x)')
plt.xlabel('x')
plt.ylabel('y')
plt.legend()
# 绘制第二个子图
plt.subplot(2, 1, 2)
plt.plot(x, y2, label='cos(x)')
plt.xlabel('x')
plt.ylabel('y')
plt.legend()
# 展示图形
plt.show()
在这个例子中,我们首先调用style.use('ggplot')选择了ggplot样式。然后,我们生成了x和y1、y2的数据用于绘制子图。接着,我们使用subplot函数创建了一个2行1列的图表,并在 个子图中绘制了sin(x)的曲线,在第二个子图中绘制了cos(x)的曲线。最后,我们使用show函数展示了图形。
通过使用matplotlib.style模块,我们可以轻松地应用各种预定义样式,使得图形更加美观和易读。
