在 Matplotlib 中使用 fivethirtyeight 样式表绘制曲线

在 Matplotlib 中使用 fivethirtyeight 样式表绘制曲线

Matplotlib 是 Python 中最流行的数据可视化库之一。它提供了许多样式表以美化图形,帮助用户更加清晰地展示数据。其中,fivethirtyeight 是一种广泛使用的样式表,它是美国知名媒体 FiveThirtyEight 网站所使用的图形风格。在本文中,我们将会介绍如何在 Matplotlib 中使用 fivethirtyeight 样式表绘制曲线。

安装 Matplotlib

在使用 Matplotlib 之前,需要先安装它。可以通过以下命令进行安装:

pip install matplotlib

导入库

安装完成后,需要将 Matplotlib 和 Pandas 库导入到 Python 环境中:

import matplotlib.pyplot as plt
import pandas as pd

准备数据

下面我们将使用 Pandas 读取一个 CSV 文件作为样例数据集。该数据集包含每个月的蔬菜出口量和进口量数据。

df = pd.read_csv('veggie_data.csv')
df.head()

输出结果:

Month Export Import
0 Jan 665 1295
1 Feb 1201 3996
2 Mar 2685 3095
3 Apr 2364 3794
4 May 1799 4068

绘制曲线

接下来就可以使用 Matplotlib 绘制曲线图了。

plt.style.use('fivethirtyeight')

plt.plot(df['Month'], df['Export'], label='Export')
plt.plot(df['Month'], df['Import'], label='Import')

plt.xlabel('Month')
plt.ylabel('Quantity')

plt.title('Vegetable Export and Import')

plt.legend()

plt.show()

这将绘制一张 fivethirtyeight 样式表的曲线图。图中分别标出了每个月的蔬菜出口量和进口量。

如何使用其它样式表

上面我们使用了 fivethirtyeight 样式表绘制曲线图,如果我们要使用其它样式表怎么办呢?Matplotlib 提供了很多内置样式表,可以通过以下代码查看:

print(plt.style.available)

输出结果:

['Solarize_Light2', '_classic_test_patch', 'bmh', 'classic', 'dark_background', 'fast', 
'fivethirtyeight', 'ggplot', 'grayscale', 'seaborn', 'seaborn-bright', 'seaborn-colorblind', 'seaborn-dark', 
'seaborn-dark-palette', 'seaborn-darkgrid', 'seaborn-deep', 'seaborn-muted', 'seaborn-notebook', 
'seaborn-paper', 'seaborn-pastel', 'seaborn-poster', 'seaborn-talk', 'seaborn-ticks', 'seaborn-white', 
'seaborn-whitegrid', 'tableau-colorblind10']

可以看到,这里提供了很多样式表可供选择。可以通过以下代码修改当前样式表:

plt.style.use('样式表名称')

总结

在 Matplotlib 中使用 fivethirtyeight 样式表绘制曲线,可以让我们的图形更漂亮、更易读。我们可以使用 Pandas 读取外部数据,使用 plt.plot() 函数绘制图形,并使用 plt.xlabel()、plt.ylabel() 和 plt.title() 函数添加标题标签。如果需要使用其它样式表,可以通过 plt.style.use() 函数实现。

Camera课程

Python教程

Java教程

Web教程

数据库教程

图形图像教程

办公软件教程

Linux教程

计算机教程

大数据教程

开发工具教程