自定义绘图坐标轴

PythonPythonBeginner
立即练习

This tutorial is from open-source community. Access the source code

💡 本教程由 AI 辅助翻译自英文原版。如需查看原文,您可以 切换至英文原版

简介

在本教程中,我们将学习如何使用Matplotlib自定义简单图表的背景、标签和刻度。

虚拟机使用提示

虚拟机启动完成后,点击左上角切换到“笔记本”标签,以访问Jupyter Notebook进行练习。

有时,你可能需要等待几秒钟让Jupyter Notebook完成加载。由于Jupyter Notebook的限制,操作验证无法自动化。

如果你在学习过程中遇到问题,随时向Labby提问。课程结束后提供反馈,我们会及时为你解决问题。


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL python(("Python")) -.-> python/ModulesandPackagesGroup(["Modules and Packages"]) python(("Python")) -.-> python/DataScienceandMachineLearningGroup(["Data Science and Machine Learning"]) matplotlib(("Matplotlib")) -.-> matplotlib/BasicConceptsGroup(["Basic Concepts"]) python(("Python")) -.-> python/BasicConceptsGroup(["Basic Concepts"]) python(("Python")) -.-> python/DataStructuresGroup(["Data Structures"]) matplotlib/BasicConceptsGroup -.-> matplotlib/importing_matplotlib("Importing Matplotlib") matplotlib/BasicConceptsGroup -.-> matplotlib/figures_axes("Understanding Figures and Axes") python/BasicConceptsGroup -.-> python/comments("Comments") python/DataStructuresGroup -.-> python/lists("Lists") python/DataStructuresGroup -.-> python/tuples("Tuples") python/ModulesandPackagesGroup -.-> python/importing_modules("Importing Modules") python/DataScienceandMachineLearningGroup -.-> python/data_visualization("Data Visualization") subgraph Lab Skills matplotlib/importing_matplotlib -.-> lab-48726{{"自定义绘图坐标轴"}} matplotlib/figures_axes -.-> lab-48726{{"自定义绘图坐标轴"}} python/comments -.-> lab-48726{{"自定义绘图坐标轴"}} python/lists -.-> lab-48726{{"自定义绘图坐标轴"}} python/tuples -.-> lab-48726{{"自定义绘图坐标轴"}} python/importing_modules -.-> lab-48726{{"自定义绘图坐标轴"}} python/data_visualization -.-> lab-48726{{"自定义绘图坐标轴"}} end

导入必要的库

我们将首先导入本教程中会用到的必要库。

import matplotlib.pyplot as plt

创建图形并设置背景

我们将使用 plt.figure() 方法创建一个图形,该方法会创建一个 matplotlib.figure.Figure 实例。我们将使用 rect.set_facecolor() 方法设置图形的背景颜色。

fig = plt.figure()
rect = fig.patch  ## 一个矩形实例
rect.set_facecolor('lightgoldenrodyellow')

向图形中添加坐标轴

我们将使用 fig.add_axes() 方法向图形中添加坐标轴。我们还将使用 rect.set_facecolor() 方法设置坐标轴的背景颜色。

ax1 = fig.add_axes([0.1, 0.3, 0.4, 0.4])
rect = ax1.patch
rect.set_facecolor('lightslategray')

自定义刻度和标签

我们将使用 ax1.tick_params() 方法自定义坐标轴的刻度和标签。我们将设置x轴标签的颜色、旋转角度和大小,以及y轴刻度的颜色、大小和宽度。

ax1.tick_params(axis='x', labelcolor='tab:red', labelrotation=45, labelsize=16)
ax1.tick_params(axis='y', color='tab:green', size=25, width=3)

显示绘图

最后,我们将使用 plt.show() 方法显示绘图。

plt.show()

总结

在本教程中,我们学习了如何使用Matplotlib自定义简单绘图的背景、标签和刻度。我们使用了 plt.figure()fig.add_axes()ax1.tick_params()plt.show() 方法来创建和显示绘图。