欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

机器学习——python之matplotlib的使用——①

程序员文章站 2022-03-18 20:40:54
...

1.安装matplotlib 库

pip install matplotlib -i https://pypi.tuna.tsinghua.edu.cn/simple//

 2.折线图


2.1折线图的绘制

from matplotlib import pyplot as plt
# x轴的位置
x = range(1, 8) 
# y轴的位置
y = [17, 17, 18, 15, 11, 11, 13]
# 传入x和y, 通过plot画折线图
plt.plot(x, y) 
# 显示
plt.show()

2.2折线的颜色形状设置

  • 设置颜色color='red'
  • 设置透明度alpha=【0-1】
  • 设置线的样式linestyle='--'
  • 设置线的宽度linewidth=3
from matplotlib import pyplot as plt

# 绘制折线(x,y)
# [1, 0, 9], [4, 5, 6]=====> (1,4), (0,5), (9,6)
"""
        **Colors**

        The supported color abbreviations are the single letter codes

        =============    ===============================
        character        color
        =============    ===============================
        ``'b'``          blue
        ``'g'``          green
        ``'r'``          red
        ``'c'``          cyan
        ``'m'``          magenta
        ``'y'``          yellow
        ``'k'``          black
        ``'w'``          white
        =============    ===============================

        **Line Styles**

        =============    ===============================
        character        description
        =============    ===============================
        ``'-'``          solid line style
        ``'--'``         dashed line style
        ``'-.'``         dash-dot line style
        ``':'``          dotted line style
        =============    ===============================
        Example format strings::

            'b'    # blue markers with default shape
            'or'   # red circles
            '-g'   # green solid line
            '--'   # dashed line with default color
            '^k:'  # black triangle_up markers connected by a dotted line
"""
plt.plot([1, 0, 9], [4, 5, 6], color='red', alpha=0.8, linestyle='--', linewidth=5)
# 显示
plt.show()

2.3折点样式

  • 设置折点marker='o'
  • 设置折点大小markersize=12
  • 设置折点边框颜色markeredgecolor='green'
  • 设置折点边框大小markeredgewidth=5
# 导入库
from matplotlib import pyplot as plt

# 绘制折线(x,y)
# [1, 0, 9], [4, 5, 6]=====> (1,4), (0,5), (9,6)
"""
        **Colors**

        The supported color abbreviations are the single letter codes

        =============    ===============================
        character        color
        =============    ===============================
        ``'b'``          blue
        ``'g'``          green
        ``'r'``          red
        ``'c'``          cyan
        ``'m'``          magenta
        ``'y'``          yellow
        ``'k'``          black
        ``'w'``          white
        =============    ===============================

        **Markers**

        =============    ===============================
        character        description
        =============    ===============================
        ``'.'``          point marker
        ``','``          pixel marker
        ``'o'``          circle marker
        ``'v'``          triangle_down marker
        ``'^'``          triangle_up marker
        ``'<'``          triangle_left marker
        ``'>'``          triangle_right marker
        ``'1'``          tri_down marker
        ``'2'``          tri_up marker
        ``'3'``          tri_left marker
        ``'4'``          tri_right marker
        ``'s'``          square marker
        ``'p'``          pentagon marker
        ``'*'``          star marker
        ``'h'``          hexagon1 marker
        ``'H'``          hexagon2 marker
        ``'+'``          plus marker
        ``'x'``          x marker
        ``'D'``          diamond marker
        ``'d'``          thin_diamond marker
        ``'|'``          vline marker
        ``'_'``          hline marker
        =============    ===============================

        **Line Styles**

        =============    ===============================
        character        description
        =============    ===============================
        ``'-'``          solid line style
        ``'--'``         dashed line style
        ``'-.'``         dash-dot line style
        ``':'``          dotted line style
        =============    ===============================
        Example format strings::

            'b'    # blue markers with default shape
            'or'   # red circles
            '-g'   # green solid line
            '--'   # dashed line with default color
            '^k:'  # black triangle_up markers connected by a dotted line
"""
plt.plot([1, 0, 9], [4, 5, 6], color='red', alpha=0.8, linestyle='--', linewidth=5, marker='o', markersize=12)
# 显示
plt.show()



2.4 设置图片的大小和保存

  • 设置图片的大小plt.figure(figsize=(20, 8))
  •  设置图片的分辨率 plt.figure(figsize=(20, 8), dpi=80)
  •   保存图片plt.savefig("./1.svg")
  • 注:在保存之前不要调用show()方法,顺序应该是savefig()——>show()
# encoding: utf-8
# time    : 2020-09-15 17:29
# author  : 进击的灰太狼
# 导入库
from matplotlib import pyplot as plt

# 设置图片大小figsize, 分辨率:dpi
plt.figure(figsize=(20, 8), dpi=80)

# 绘制折线(x,y)
# [1, 0, 9], [4, 5, 6]=====> (1,4), (0,5), (9,6)
"""
        **Colors**

        The supported color abbreviations are the single letter codes

        =============    ===============================
        character        color
        =============    ===============================
        ``'b'``          blue
        ``'g'``          green
        ``'r'``          red
        ``'c'``          cyan
        ``'m'``          magenta
        ``'y'``          yellow
        ``'k'``          black
        ``'w'``          white
        =============    ===============================
        
        **Markers**

        =============    ===============================
        character        description
        =============    ===============================
        ``'.'``          point marker
        ``','``          pixel marker
        ``'o'``          circle marker
        ``'v'``          triangle_down marker
        ``'^'``          triangle_up marker
        ``'<'``          triangle_left marker
        ``'>'``          triangle_right marker
        ``'1'``          tri_down marker
        ``'2'``          tri_up marker
        ``'3'``          tri_left marker
        ``'4'``          tri_right marker
        ``'s'``          square marker
        ``'p'``          pentagon marker
        ``'*'``          star marker
        ``'h'``          hexagon1 marker
        ``'H'``          hexagon2 marker
        ``'+'``          plus marker
        ``'x'``          x marker
        ``'D'``          diamond marker
        ``'d'``          thin_diamond marker
        ``'|'``          vline marker
        ``'_'``          hline marker
        =============    ===============================

        **Line Styles**

        =============    ===============================
        character        description
        =============    ===============================
        ``'-'``          solid line style
        ``'--'``         dashed line style
        ``'-.'``         dash-dot line style
        ``':'``          dotted line style
        =============    ===============================
        Example format strings::

            'b'    # blue markers with default shape
            'or'   # red circles
            '-g'   # green solid line
            '--'   # dashed line with default color
            '^k:'  # black triangle_up markers connected by a dotted line
"""
plt.plot([1, 0, 9], [4, 5, 6], color='red', alpha=0.8, linestyle='--', linewidth=5, marker='o', markersize=12)


# 保存图片
plt.savefig("./1.svg", bbox_inches='tight')
# 显示
plt.show()

2.5 绘制X轴和Y轴的刻度

  • plt.xticks(ticks=None, labels=None)
  • plt.yticks(ticks=None, labels=None)
  • ticks:确定有多少个刻度
  • labels:每个刻度的具体显示值
# encoding: utf-8
# time    : 2020-09-15 17:29
# author  : 进击的灰太狼
# 导入库
import random
from matplotlib import pyplot as plt

# 设置图片大小figsize, 分辨率:dpi
# plt.figure(figsize=(20, 8), dpi=80)

# 绘制折线(x,y)
# [1, 0, 9], [4, 5, 6]=====> (1,4), (0,5), (9,6)
"""
        **Colors**

        The supported color abbreviations are the single letter codes

        =============    ===============================
        character        color
        =============    ===============================
        ``'b'``          blue
        ``'g'``          green
        ``'r'``          red
        ``'c'``          cyan
        ``'m'``          magenta
        ``'y'``          yellow
        ``'k'``          black
        ``'w'``          white
        =============    ===============================
        
        **Markers**

        =============    ===============================
        character        description
        =============    ===============================
        ``'.'``          point marker
        ``','``          pixel marker
        ``'o'``          circle marker
        ``'v'``          triangle_down marker
        ``'^'``          triangle_up marker
        ``'<'``          triangle_left marker
        ``'>'``          triangle_right marker
        ``'1'``          tri_down marker
        ``'2'``          tri_up marker
        ``'3'``          tri_left marker
        ``'4'``          tri_right marker
        ``'s'``          square marker
        ``'p'``          pentagon marker
        ``'*'``          star marker
        ``'h'``          hexagon1 marker
        ``'H'``          hexagon2 marker
        ``'+'``          plus marker
        ``'x'``          x marker
        ``'D'``          diamond marker
        ``'d'``          thin_diamond marker
        ``'|'``          vline marker
        ``'_'``          hline marker
        =============    ===============================

        **Line Styles**

        =============    ===============================
        character        description
        =============    ===============================
        ``'-'``          solid line style
        ``'--'``         dashed line style
        ``'-.'``         dash-dot line style
        ``':'``          dotted line style
        =============    ===============================
        Example format strings::

            'b'    # blue markers with default shape
            'or'   # red circles
            '-g'   # green solid line
            '--'   # dashed line with default color
            '^k:'  # black triangle_up markers connected by a dotted line
"""
# plt.plot([1, 0, 9], [4, 5, 6], color='red', alpha=0.8, linestyle='--', linewidth=5, marker='o', markersize=12)
# x轴的位置
x = range(2, 26, 2)
# y轴的位置
y = [random.randint(15, 30) for i in x]
x_ticks_label = ["{}:00".format(i) for i in x]
# plt.xticks(range(1, 30))
# 第一个参数:确定有多少个刻度,第二个参数:每个刻度的具体显示值,rotation = 45 让字旋转45度
plt.xticks(x, x_ticks_label, rotation=45)
# 设置y轴的刻度标签
y_ticks_label = ["{}℃".format(i) for i in range(min(y), max(y)+1)]
plt.yticks(range(min(y), max(y)+1), y_ticks_label)

plt.plot(x, y, color='red', alpha=0.8, linestyle='--', linewidth=5, marker='o', markersize=12)
# 保存图片
#  bbox_inches='tight' 不会忽略不可见的轴
# plt.savefig("./1.svg", bbox_inches='tight')

# 显示
plt.show()

2.6 设置显示中文

windows查看字体:C:\Windows\Fonts

  • 方法①
# 用来正常显示中文标签
plt.rcParams['font.sans-serif'] = ['SimHei']
# 用来正常显示负号
plt.rcParams['axes.unicode_minus'] = False
# 设置图片标题
plt.title("折线图")
plt.ylabel("温度")
plt.xlabel("时间")
  • 方法②
from matplotlib import font_manager
my_font = font_manager.FontProperties(fname="C:\\Windows\\Fonts\\simsun.ttc",)
# 设置图片标题
plt.title("折线图", fontproperties=my_font, size=18)
plt.ylabel("温度", fontproperties=my_font, size=12)
plt.xlabel("时间", fontproperties=my_font, size=12)

2.7 一图多线

# encoding: utf-8
# time    : 2020-09-15 17:29
# author  : 进击的灰太狼
# 导入库
import random
from matplotlib import pyplot as plt
from matplotlib import font_manager
my_font = font_manager.FontProperties(fname="C:\\Windows\\Fonts\\simsun.ttc", size=24)
# 用来正常显示中文标签
plt.rcParams['font.sans-serif'] = ['SimHei']
# 用来正常显示负号
plt.rcParams['axes.unicode_minus'] = False
# 假设大家在30岁的时候,根据自己的实际情况,统计出来你和你同事各自从11岁到30岁每年交的男/女朋友的数量如列表y1和y2,请在一个图中绘制出该数据的折线图,从而分析每年交朋友的数量走势。
y1 = [1, 0, 1, 1, 2, 4, 3, 4, 4, 5, 6, 5, 4, 3, 3, 1, 1, 1, 1, 1]
y2 = [1, 0, 3, 1, 2, 2, 3, 4, 3, 2, 1, 2, 1, 1, 1, 1, 1, 1, 1, 1]
x = range(11, 31)
# 设置图形
plt.figure(figsize=(20, 8), dpi=80)

plt.plot(x, y1, color='red', label='自己')

plt.plot(x, y2, color='blue', label='朋友')
# 设置x轴刻度
x_tick_labels = ['{}岁'.format(i) for i in x]
plt.xticks(x, x_tick_labels, rotation=45, fontproperties=my_font, size=18)
plt.yticks(fontproperties=my_font, size=18)
# 绘制网格(网格也是可以设置线的样式)
# alpha=0.4 设置透明度
plt.grid(alpha=0.4)

# 添加图例(注意:只有在这里需要添加prop参数是显示中文,其他的都用fontproperties)
# 设置位置loc : upper left、 lower left、 center left、 upper center
plt.legend(loc='upper right', prop=my_font)

# 展示
plt.show()

2.8 一图多个坐标系子图

# encoding: utf-8
# time    : 2020-09-15 17:29
# author  : 进击的灰太狼
# 导入库
# add_subplot方法----给figure新增子图
import numpy as np
import matplotlib.pyplot as plt
x = np.arange(1, 100)
# 新建figure对象
fig = plt.figure(figsize=(20, 10), dpi=80)
# 新建子图1
ax1 = fig.add_subplot(2, 2, 1)
ax1.plot(x, x)
# 新建子图2
ax2 = fig.add_subplot(2, 2, 2)
ax2.plot(x, x ** 2)
ax2.grid(color='r', linestyle='--', linewidth=1, alpha=0.3)
# 新建子图3
ax3 = fig.add_subplot(2, 2, 3)
ax3.plot(x, np.log(x))
plt.show()

2.9 设置坐标轴范围

import matplotlib.pyplot as plt
import numpy as np
x = np.arange(-10, 11, 1)
y = x**2
plt.plot(x, y)
# 可以调x轴的左右两边
# 只调一边
# 调节x轴
plt.xlim(xmin=-10)
plt.xlim(xmax=10)
# 调节y轴
plt.ylim(ymin=0)
plt.ylim(ymax=100)
plt.show()

2.10 改变坐标轴的默认显示方式

import matplotlib.pyplot as plt

y = range(0, 14, 2)
# x轴的位置
x = [-3, -2, -1, 0, 1, 2, 3]
# plt.figure(figsize=(20, 8), dpi=80)

# 获得当前图表的图像
ax = plt.gca()

# 设置图型的包围线
ax.spines['right'].set_color('none')
ax.spines['top'].set_color('none')
ax.spines['bottom'].set_color('blue')
ax.spines['left'].set_color('red')

# 设置底边的移动范围,移动到y轴的0位置,'data':移动轴的位置到交叉轴的指定坐标
ax.spines['bottom'].set_position(('data', 0))
ax.spines['left'].set_position(('data', 0))

plt.plot(x, y)
plt.show()