Python matplotlib之折线图的各种样式与画法总结

yizhihongxing

Python matplotlib之折线图的各种样式与画法总结

1. 简介

matplotlib 是 Python 语言下的一个绘图库,它提供了一种类似 MATLAB 的绘图方式。matplotlib 不仅能够简单方便地生成各种折线图,而且还支持很多自定义样式和参数设置。

本文将围绕 matplotlib 绘制折线图进行详细的讲解,包括:

  • 如何安装 matplotlib
  • 如何进行基本绘图操作
  • 折线图的各种样式及代码示范
  • 折线图的数据处理及示例分析

2. 安装 matplotlib

使用 pip 命令可以简单方便地安装 matplotlib 库。

pip install matplotlib

常见问题:

如果报错信息显示 matplotlib 找不到系统依赖的包 libfreetype.6.dylib,解决方式如下:

  1. brew install freetype
  2. pip install --no-cache-dir -I --ignore-installed matplotlib

3. 基本绘图操作

绘制一个简单的线性折线图,需要几个简单的步骤:

  1. 生成数据
  2. 创建画布和坐标系
  3. 将数据放置在坐标系上并设置样式
  4. 设置坐标轴信息等图形参数
  5. 显示图形

下面是一个简单示例代码:

import matplotlib.pyplot as plt

# 生成数据
x = [1, 2, 3, 4, 5, 6]
y = [2, 3, 5, 8, 11, 14]

# 创建画布和坐标系
fig, ax = plt.subplots()

# 添加数据到坐标系上并设置样式
ax.plot(x, y, color='red', linewidth=2, linestyle='--', label='Line Name')

# 设置坐标轴信息等图形参数
ax.set_xlabel('X Label')
ax.set_ylabel('Y Label')
ax.set_title('Title')
ax.grid(True)
ax.legend(loc='best')

# 显示图形
plt.show()

可以看到,我们调用了 plot 方法将数据放置在坐标系上,该方法支持很多样式的设置,比如 colorlinewidthlinestyle 等。同时,我们还通过更改坐标轴标签、标题、网格和图例等内容,让图形看起来更加美观易懂。

4. 折线图的各种样式及代码示范

在本节中,我们将针对折线图的多种样式进行详细的介绍,具体包括以下内容:

  • 线性折线图
  • 曲线折线图
  • 填充面积折线图
  • 点状折线图
  • 标记文本折线图
  • 带误差线折线图
  • 双轴折线图

4.1 线性折线图

线性折线图是最为常见的折线图类型。在 matplotlib 中,可以通过 plot 函数快速绘制出这种类型的折线图。

import matplotlib.pyplot as plt

# 生成数据
x = [1, 2, 3, 4, 5, 6]
y = [2, 3, 5, 8, 11, 14]

# 创建画布和坐标系
fig, ax = plt.subplots()

# 添加数据到坐标系上并设置样式
ax.plot(x, y, color='red', linewidth=2, linestyle='--')

# 显示图形
plt.show()

4.2 曲线折线图

除了线性折线图外,还有一类叫做曲线折线图的图形。它们可以通过将坐标系切换为极坐标系后再进行绘制。

import numpy as np
import matplotlib.pyplot as plt

# 生成数据
theta = np.linspace(0, 2*np.pi, 100)
r = np.sin(3*theta)

# 创建画布和坐标系
fig, ax = plt.subplots(subplot_kw={'projection': 'polar'})

# 添加数据到坐标系上并设置样式
ax.plot(theta, r, color='blue')

# 显示图形
plt.show()

4.3 填充面积折线图

在 matplotlib 中,我们还可以通过 fill_between 函数绘制填充面积折线图。

import matplotlib.pyplot as plt

# 生成数据
x = [1, 2, 3, 4, 5, 6]
y = [2, 3, 5, 8, 11, 14]

# 创建画布和坐标系
fig, ax = plt.subplots()

# 添加数据到坐标系上并设置样式
ax.fill_between(x, y, color='g', alpha=0.3)
ax.plot(x, y, color='g', linewidth=2, linestyle='--')

# 显示图形
plt.show()

4.4 点状折线图

在 matplotlib 中,我们可以通过 scatter 函数快速绘制出点状折线图。

import matplotlib.pyplot as plt

# 生成数据
x = [1, 2, 3, 4, 5, 6]
y = [2, 3, 5, 8, 11, 14]

# 创建画布和坐标系
fig, ax = plt.subplots()

# 添加数据到坐标系上并设置样式
ax.scatter(x, y, color='red', marker='o')

# 显示图形
plt.show()

4.5 标记文本折线图

标记文本折线图可以通过 annotate 函数实现。它可以在坐标系上添加文本标注和箭头标记等元素。

import matplotlib.pyplot as plt

# 生成数据
x = [1, 2, 3, 4, 5, 6]
y = [2, 3, 5, 8, 11, 14]

# 创建画布和坐标系
fig, ax = plt.subplots()

# 添加数据到坐标系上并设置样式
ax.plot(x, y, color='blue')
ax.annotate('Start Here', xy=(x[0], y[0]), xytext=(2, 8), fontsize=10,
            arrowprops=dict(facecolor='yellow', arrowstyle='->'))

# 显示图形
plt.show()

4.6 带误差线折线图

在 matplotlib 中,我们可以使用 errorbar 函数添加误差线。

import matplotlib.pyplot as plt

# 生成数据
x = [1, 2, 3, 4, 5, 6]
y = [2, 3, 5, 8, 11, 14]
y_error = [0.3, 0.4, 0.2, 0.6, 0.8, 0.5]

# 创建画布和坐标系
fig, ax = plt.subplots()

# 添加数据到坐标系上并设置样式
ax.errorbar(x, y, yerr=y_error, fmt='-o', capsize=3)

# 显示图形
plt.show()

4.7 双轴折线图

双轴折线图是一种非常实用的图表类型,它可以在同一个图表中绘制两个不同的数据集,每个数据集具有自己的轴。在 matplotlib 中,我们可以通过 twinx 函数实现双轴折线图。

import matplotlib.pyplot as plt
import numpy as np

# 生成数据
x = np.linspace(0, 10, 100)
y1 = np.sin(x)
y2 = np.cos(x)

# 创建画布和坐标系
fig, ax1 = plt.subplots()

# 添加数据到坐标系上并设置样式
ax1.plot(x, y1, color='blue')
ax1.set_xlabel('X axis')
ax1.set_ylabel('Y1', color='blue')
ax1.tick_params(axis='y', labelcolor='blue')

ax2 = ax1.twinx()
ax2.plot(x, y2, color='red')
ax2.set_ylabel('Y2', color='red')
ax2.tick_params(axis='y', labelcolor='red')

# 显示图形
plt.show()

5. 折线图的数据处理与示例分析

在本节中,我们将介绍如何通过实际案例进行折线图的数据处理及分析。

数据源:https://data.giss.nasa.gov/gistemp/

该数据集记录了全球降水、温度和气候变化情况,本文选择其中的温度数据进行折线图分析。

5.1 数据分析

import pandas as pd
import matplotlib.pyplot as plt

# 读取数据集
df_climate = pd.read_csv('GLB.Ts_dSST.csv', skiprows=2)

# 数据处理
# 取最近一年的数据
current_year = df_climate['Year'].max()
df_climate = df_climate[df_climate['Year'] == current_year]
# 提取数据中的月份温度信息
cols = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun',
        'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
df_climate = df_climate[cols].T.reset_index()
df_climate.columns = ['Month', 'Temp']
# 去掉没有数据的月份
df_climate = df_climate.dropna()

# 绘制折线图
fig, ax = plt.subplots()
ax.plot(df_climate['Month'], df_climate['Temp'])
ax.set_xticklabels(cols)
ax.set_xlabel('Month')
ax.set_ylabel('Temperature Anomaly (°C)')
ax.set_title(f'Global Temperature Anomalies in {current_year}')
ax.grid(True)

# 显示图形
plt.show()

如上方法(数据源在上文中附上),我们将温度数据读取到 DataFrame 中,并处理得到最近一年(2019)的各月份温度数据。最后,我们通过 plot 函数绘制折线图,可以很清晰地看到全球的温度变化情况。

5.2 结论

通过以上的温度数据的折线图,我们可以看到全球温度变化的趋势向上,特别是近年来变化幅度加大。因此,对于温室效应和全球气候变化的问题,我们应该引起高度重视和实际行动,尽可能地减少对环境的压力。

本站文章如无特殊说明,均为本站原创,如若转载,请注明出处:Python matplotlib之折线图的各种样式与画法总结 - Python技术站

(0)
上一篇 2023年6月13日
下一篇 2023年6月13日

相关文章

  • pandas.DataFrame.drop_duplicates 用法介绍

    pandas.DataFrame.drop_duplicates用法介绍 介绍 pandas.DataFrame.drop_duplicates()方法返回一个DataFrame,其中包含DataFrame重复行的条目。在数据处理中,通常需要删除重复的行,以保证数据的一致性和准确性。 语法 DataFrame.drop_duplicates(subset=N…

    python 2023年5月14日
    00
  • Pandas 数据读取与写入数据读取与写入

    当我们进行数据处理和分析时,读取数据和将数据写入到文件中是很重要的一步。Pandas是Python语言中数据处理和分析的一个强大的库,可以方便地对各种类型的数据进行读取和写入操作。接下来,我会详细讲解如何使用Pandas进行数据读取和写入。 Pandas 数据读取 读取 CSV 文件 Pandas内置了很多读取不同文件格式的函数,其中最常用的是读取CSV文件…

    python-answer 2023年3月27日
    00
  • MySQL存储Json字符串遇到的问题与解决方法

    MySQL存储Json字符串遇到的问题与解决方法 在进行开发时,我们通常会使用MySQL数据库存储数据。MySQL 5.7版本及以上版本支持存储Json字符串,但是在实际操作中会遇到一些问题和坑点。本文将详细讲解MySQL存储Json字符串遇到的问题以及解决方法。 问题 在MySQL中存储JSON字符串时,可能会遇到以下问题: 插入JSON字符串失败 SQL…

    python 2023年5月14日
    00
  • Pandas爆炸函数的使用技巧

    关于Pandas爆炸函数的使用技巧,我们需要先介绍Pandas库中用于处理复杂数据结构和数据分析的数据类型Series和DataFrame。 Series是一种类似于一维数组的数据类型,它由数据值和索引组成。 Series有很多内置的函数,可以进行分组、排序、过滤、映射、元素访问等操作。DataFrame是一个表格型的数据结构,由多个Series组成。它有多…

    python 2023年5月14日
    00
  • 使用Regex从给定的Pandas DataFrame的指定列中提取日期

    首先,我们需要安装Python中的正则表达式库re。在命令行或者jupyter notebook中输入以下命令进行安装: !pip install re 接下来,我们需要对DataFrame中的日期列进行正则匹配并提取出日期。 假设我们有以下DataFrame: import pandas as pd data = {‘日期’: [‘2022/05/01 1…

    python-answer 2023年3月27日
    00
  • 如何在Pandas中创建一个带有可点击的超链接到本地文件的表格

    要在 Pandas 中创建一个带有可点击的超链接到本地文件的表格,可以使用 Pandas 的 style 方法。具体步骤如下: 导入 Pandas 和 os 模块,并读取数据到 Pandas 的 DataFrame 中。 import pandas as pd import os # 读取数据到 Pandas 的 DataFrame df = pd.read…

    python-answer 2023年3月27日
    00
  • Pandas数据类型转换df.astype()及数据类型查看df.dtypes的使用

    Pandas是Python中数据分析的重要库之一,数据类型转换和查看数据类型是数据分析的基础,本攻略聚焦于Pandas数据类型转换及数据类型查看的使用。 Pandas数据类型转换df.astype()的使用 1.语法格式 DataFrame.astype(dtype, copy=True, errors=’raise’) 2.参数说明 dtype:指定数据类…

    python 2023年5月14日
    00
  • pandas dataframe drop函数介绍

    Pandas DataFrame Drop函数介绍 在使用Pandas读取数据后,我们可能需要对数据进行处理和清洗。其中,删除DataFrame中的某些行或列是常见的操作之一。Pandas中提供了df.drop()函数来满足这一需求。 函数语法 df.drop(labels=None, axis=0, index=None, columns=None, le…

    python 2023年5月14日
    00
合作推广
合作推广
分享本页
返回顶部