matplotlib绘制折线图

matplotlib绘制折线图,第1张

matplotlib绘制折线图

目录

开始使用

图片大小和像素

坐标轴刻度

文本和标签

线条

网格

保存图片

通用设置(重要)


开始使用

随手取一组数据: 伦敦的一年中每月的平均最高和最低气温

from math import pi
from icecream import ic
import matplotlib
import matplotlib.pyplot as plt

import numpy as np
from numpy.lib.function_base import gradient

x = np.arange(0, 24, 2)
y1 = np.array([2, 2, 4, 6, 9, 12, 14, 13, 11, 9, 5, 3]) # 最低气温
y2 = np.array([7, 8, 10, 13, 17, 20, 22, 22, 19, 15, 10, 8]) # 最高气温
# 如果没有什么需求, 可以直接显示plot.show()
plt.show()

但是在matplotlib中可以有很多的设置:

图片大小和像素
plt.figure(figsize=(10, 10), dpi=80)
# figsize是长和宽, dpi是像素
坐标轴的刻度值
_xticks = np.array(range(0, 24, 2))

plt.xticks(_xticks, labels=["{} 时".format(i) for i in _xticks])
# 设置x轴的刻度值
plt.yticks([0, 5, 10, 15, 20], labels=["0℃", "5℃", "10℃", "15℃", "20℃"])
# label是设置所在刻度的标签
文本和标签
plt.xlabel("时间") # x轴的标签
plt.ylabel("温度") # y轴的标签
plt.title("伦敦各个月份气温变化的情况") # 图像的标题
线条
plt.plot(x, y1, label='最低气温', linestyle='--',color='r')
plt.plot(x, y2, label='最高气温', linestyle='-', color='b')
plt.legend() # 一定要加上这行,上面的才能生效
网格
plt.grid() # 给图像设置网格
保存图片
plt.savefig("resources/t1.png")
# 保存图片,VScode中的路径似乎都是以项目文件为相对路径
# 主要一定要在show()之前保存, show()之后图片就不见了
通用设置(重要)

matplotlib.rc是通用的设置图像的函数, group是设置的对象, 后面的参数是设置的属性,比如下面这个例子

matplotlib.rc(group='lines', lw=2, color='b')
# group是设置哪种元素, 这里是设置线条,并设置了线条宽度和颜色

matplotlib.rc(group='font', family='SimHei')
# 设置字体, 默认的字体不支持中文

下面是rc函数的注释:

可以看出设置的对象有lines(线条), axes(坐标轴),font(等) 

能设置的属性和别名也列举的比较清楚

def rc(group, **kwargs):
    """
    Set the current `.rcParams`.  *group* is the grouping for the rc, e.g.,
    for ``lines.linewidth`` the group is ``lines``, for
    ``axes.facecolor``, the group is ``axes``, and so on.  Group may
    also be a list or tuple of group names, e.g., (*xtick*, *ytick*).
    *kwargs* is a dictionary attribute name/value pairs, e.g.,::

      rc('lines', linewidth=2, color='r')

    sets the current `.rcParams` and is equivalent to::

      rcParams['lines.linewidth'] = 2
      rcParams['lines.color'] = 'r'

    The following aliases are available to save typing for interactive users:

    =====   =================
    Alias   Property
    =====   =================
    'lw'    'linewidth'
    'ls'    'linestyle'
    'c'     'color'
    'fc'    'facecolor'
    'ec'    'edgecolor'
    'mew'   'markeredgewidth'
    'aa'    'antialiased'
    =====   =================

    Thus you could abbreviate the above call as::

          rc('lines', lw=2, c='r')

    Note you can use python's kwargs dictionary facility to store
    dictionaries of default parameters.  e.g., you can customize the
    font rc as follows::

      font = {'family' : 'monospace',
              'weight' : 'bold',
              'size'   : 'larger'}
      rc('font', **font)  # pass in the font dict as kwargs

    This enables you to easily switch between several configurations.  Use
    ``matplotlib.style.use('default')`` or :func:`~matplotlib.rcdefaults` to
    restore the default `.rcParams` after changes.

    Notes
    -----
    Similar functionality is available by using the normal dict interface, i.e.
    ``rcParams.update({"lines.linewidth": 2, ...})`` (but ``rcParams.update``
    does not support abbreviations or grouping).
    """

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/zaji/5710480.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-17
下一篇 2022-12-17

发表评论

登录后才能评论

评论列表(0条)

保存