matplotlib学习记录

一、库的导入

# 导入matplotlib库
import matplotlib.pyplot as plt

二、折线显示与参数设置

1、简单图形显示

x = range(1, 8)  # x轴数据
y = [17, 17, 18, 25, 11, 12, 13]  # y轴数据
# 传入x和y,通过plot画折线图
plt.plot(x, y) # 设置x,y轴的值,注意x和y的值要一一对应
plt.show()  # 显示图形

显示结果:

2、设置折线图的颜色,透明度,线宽,线型

x = range(1, 8)
y = [17, 17, 18, 25, 11, 12, 13]
# 传入x和y,通过plot画折线图,设置颜色为黄色,透明度为0.5,线宽为2,线型为虚线
plt.plot(x, y, color='yellow', alpha=0.5, linewidth=2, linestyle='--')
plt.show()  # 显示图形

显示结果:

3、设置折点样式

x = range(1, 8)
y = [17, 17, 18, 25, 11, 12, 13]
# 传入x和y,通过plot画折线,设置折点样式为圆点
plt.plot(x, y, marker='o')
plt.show()  # 显示图形

显示结果:

4、设置画布的大小

import random

x = range(2, 26, 2)  #x轴数据
y = [random.randint(15, 30) for i in x]
#设置画布
plt.figure(figsize=(20, 5), dpi=80)  #设置画布大小为20*5,分辨率为80
#画折线图
plt.plot(x, y)
plt.show()

显示结果:

5、绘制x轴和y轴的刻度

x = range(2, 26, 2)  # x轴数据,时间刻度,2点到24点,步长为2
y = [random.randint(15, 30) for i in x] # 随机生成[15,30]之间的随机数作为y轴数据
# 设置画布
plt.figure(figsize=(20, 8), dpi=80)
#设置x轴刻度标签
x_ticks_label = [f"{i}:00" for i in x]
# 设置x轴刻度标签,旋转45度,x和x_ticks_label中的元素数量要相同
plt.xticks(x, x_ticks_label, rotation=45)  

#设置y轴刻度标签
y_ticks_label = [f"{i}°C" for i in range(min(y), max(y) + 1)]
print(y_ticks_label)

# y的个数和y_ticks_label的个数必须一致
plt.yticks(range(min(y), max(y) + 1), y_ticks_label)  # 设置y轴刻度标签

plt.plot(x, y)
plt.show()  # 显示图形

输出结果:

['16°C', '17°C', '18°C', '19°C', '20°C', '21°C', '22°C', '23°C', '24°C', '25°C', '26°C', '27°C', '28°C', '29°C', '30°C']

显示结果:

6、设置标签与中文字体显示

x = range(120)
y = [random.randint(10, 30) for i in range(120)]

# 设置画布
plt.figure(figsize=(20, 8), dpi=80)

# 设置x轴和y轴的刻度标签
plt.plot(x, y)

from matplotlib import font_manager

#设置字体,windows下使用simsun.ttc字体,字体大小固定位18
my_font = font_manager.FontProperties(fname='C:\\Windows\\Fonts\\simsun.ttc', size=18)

# 设置x轴标签字体,如果不设置字体,显示的中文会乱码
plt.xlabel('时间', rotation=45, fontproperties=my_font)  

# 设置y轴标签字体,labelpad为标签(“次数”)与y轴的距离,数字越大离得越远
plt.ylabel("次数", rotation=0, labelpad=20, fontproperties=my_font)  

# 设置标题
plt.title("每分钟跳动次数", color='red', fontproperties=my_font)

plt.show()  # 显示图形

显示结果:

7、一图多线

import matplotlib.pyplot as plt
from matplotlib import font_manager

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, label='myself', color='orange')  # 画线1
plt.plot(x, y2, label='others', color='blue')  # 画线2

# 设置x轴刻度标签
xticks_label = [f"{i}岁" for i in x]

# 设置字体
my_font = font_manager.FontProperties(fname='C:\\Windows\\Fonts\\simsun.ttc', size=18)

# 设置x轴刻度标签
plt.xticks(x, xticks_label, rotation=45, fontproperties=my_font)  # 设置x轴刻度标签,旋转45度

# 绘制网格(网格也是可以设置线的样式的)
# alpha=0.4 设置透明度
plt.grid(alpha=0.4)

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

plt.show()  # 显示图形

显示结果:

8、一张画布设置多个子图

import numpy as np
import matplotlib.pyplot as plt
from matplotlib import font_manager

x = np.arange(1, 100)
# fig得到的是整个画布,axes得到的是子图
fig, axes = plt.subplots(2, 2)  # 创建2行2列的子图
# 设置子图的标题
my_font = font_manager.FontProperties(fname='C:\\Windows\\Fonts\\simsun.ttc', size=18)  # 设置字体
fig.suptitle('子图示例', fontsize=20, fontproperties=my_font)  # 设置整个画布的标题

# 设置画布大小
fig.set_size_inches(10, 5)  # 第一个参数是宽度,第二个参数是高度

ax1 = axes[0, 0]  # 第一行第一列
ax2 = axes[0, 1]  # 第一行第二列
ax3 = axes[1, 0]  # 第二行第一列
ax4 = axes[1, 1]  # 第二行第二列

ax1.plot(x, x)
ax2.plot(x, -x)
ax3.plot(x, x ** 2)
# 给第三个子图设置网格线颜色,线型,线宽,透明度
ax3.grid(color='r', linestyle='--', linewidth=1, alpha=0.5)  
ax4.plot(x, np.sin(x))
plt.show()

显示结果:

9、设置多个子图的第二种操作

import numpy as np
import matplotlib.pyplot as plt

x = np.arange(1, 100)

#新建figure对象
fig = plt.figure(figsize=(20, 10), dpi=80)
# 将figure对象分割成4个子图,其中ax1占第一个子位置,ax2占第二个子位置,ax3占第三个子位置,ax4占第四个子位置
ax1 = fig.add_subplot(2, 2, 1)  #子图在第1行第1列
ax2 = fig.add_subplot(2, 2, 2)  #子图在第1行第2列
ax3 = fig.add_subplot(2, 2, 3)  #子图在第2行第1列
ax4 = fig.add_subplot(2, 2, 4)  #子图在第2行第2列

ax1.plot(x, x)
ax2.plot(x, -x)
ax3.plot(x, x ** 2)
ax3.grid(color='r', linestyle='--', linewidth=1, alpha=0.5)  # 设置网格线颜色,线型,线宽,透明度
ax4.plot(x, np.sin(x))

plt.show()

显示结果:

三、绘制散点图

import matplotlib.pyplot as plt
import numpy as np

y = [11, 17, 16, 11, 12, 11, 12, 6, 6, 7, 8, 9, 12, 15, 14, 17, 18, 21, 16, 17, 20, 14, 15, 15, 15, 19, 21, 22, 22, 22,
     23]

y2 = [np.random.randint(10, 23) for i in range(31)]

x = range(1, 32)

# 设置图形大小
plt.figure(figsize=(20, 8), dpi=80)

# 使用scatter绘制散点图,设置散点的颜色,形状和大小
plt.scatter(x, y, label="3月份", color='orange', marker='o', s=200)

plt.scatter(x, y2, label="4月份", color='blue', marker='*', s=200)

# 设置中文字体
my_font = font_manager.FontProperties(fname='C:\\Windows\\Fonts\\simsun.ttc', size=18)

# 设置x轴刻度标签
xticks_label = [f"{day}日" for day in x]
plt.xticks(x, xticks_label, rotation=45, fontproperties=my_font)
plt.xlabel("日期", fontproperties=my_font)

# 设置y轴刻度标签
yticks_label = [f"{temp}°C" for temp in range(min(y), max(y) + 4)]
plt.yticks(range(min(y), max(y) + 4), yticks_label, fontproperties=my_font)
plt.ylabel("温度", fontproperties=my_font)

plt.grid(alpha=0.4)
# 设置图例
plt.legend(prop=my_font, loc='upper left')
plt.show()

显示结果:

四、绘制条形图

import matplotlib.pyplot as plt
from matplotlib import font_manager

my_font = font_manager.FontProperties(fname='C:\\Windows\\Fonts\\simsun.ttc', size=16)
a = ['流浪地球', '疯狂的外星人', '飞驰人生', '大黄蜂', '熊出没·原始时代', '新喜剧之王']
b = [38.13, 19.85, 14.89, 11.36, 6.47, 5.93]  # 票房

plt.figure(figsize=(20, 8), dpi=80)  # 设置画布大小

# 绘制条形图的方法

# rects是返回的对象,里面包含了每个条形图的对象,可以对每个条形图进行设置
# 第一个参数range(len(a))设置的是每个条形在x轴的位置,b设置的是每个条形的高度,width设置条形的宽度
rects = plt.bar(range(len(a)), b, width=0.35, color='red', alpha=0.5)

# 设置x轴的刻度显示
plt.xticks(range(len(a)), a, fontproperties=my_font, rotation=45, fontsize=20)

# 设置y轴刻度的字体大小
# plt.yticks(range(0, 41, 5), fontsize=16) # 设置条形图的y轴刻度以及字体大小
plt.yticks(fontsize=16) # 一般条形图的刻度都是自适应的,无需自己调整
# 修改y轴的刻度范围
# plt.ylim(0, 45)

for rect in rects:  # 给条形图添加数值标签
    height = rect.get_height()
    # 第一个参数是x轴坐标,第二个参数是y轴坐标,第三个参数是数值标签,ha='center'表示水平居中,va='bottom'表示垂直居下,fontproperties设置字体
    # rect.get_x() + rect.get_width() / 2表示条形图的中心点的x轴坐标
    # 设置ha为'center',则代表会以rect.get_x() + rect.get_width() / 2的位置进行中心对齐
    # height + 0.3表示数值标签的位置,数值标签距离条形图的底部0.3的距离
    # str(height)表示数值标签的内容
    # ha表示的是字体的水平对齐方式,va表示的是字体的垂直对齐方式
    # ha还有'right','left','center',va还有'top','bottom','center'
    plt.text(rect.get_x() + rect.get_width() / 2, height + 0.3, str(height), ha='center', va='bottom',
             fontproperties=my_font)

plt.show()

显示结果:

五、绘制直方图

time = [131, 98, 125, 131, 124, 139, 131, 117, 128, 108, 135, 138, 131, 102, 107, 114,
        119, 128, 121, 142, 127, 130, 124, 101, 110, 116, 117, 110, 128, 128, 115, 99,
        136, 126, 134, 95, 138, 117, 111, 78, 132, 124, 113, 150, 110, 117, 86, 95, 144,
        105, 126, 130, 126, 130, 126, 116, 123, 106, 112, 138, 123, 86, 101, 99, 136, 123,
        117, 119, 105, 137, 123, 128, 125, 104, 109, 134, 125, 127, 105, 120, 107, 129, 116,
        108, 132, 103, 136, 118, 102, 120, 114, 105, 115, 132, 145, 119, 121, 112, 139, 125,
        138, 109, 132, 134, 156, 106, 117, 127, 144, 139, 139, 119, 140, 83, 110, 102, 123,
        107, 143, 115, 136, 118, 139, 123, 112, 118, 125, 109, 119, 133, 112, 114, 122, 109,
        106, 123, 116, 131, 127, 115, 118, 112, 135, 115, 146, 137, 116, 103, 144, 83, 123,
        111, 110, 111, 100, 154, 136, 100, 118, 119, 133, 134, 106, 129, 126, 110, 111, 109,
        141, 120, 117, 106, 149, 122, 122, 110, 118, 127, 121, 114, 125, 126, 114, 140, 103,
        130, 141, 117, 106, 114, 121, 114, 133, 137, 92, 121, 112, 146, 97, 137, 105, 98,
        117, 112, 81, 97, 139, 113, 134, 106, 144, 110, 137, 137, 111, 104, 117, 100, 111,
        101, 110, 105, 129, 137, 112, 120, 113, 133, 112, 83, 94, 146, 133, 101, 131, 116,
        111, 84, 137, 115, 122, 106, 144, 109, 123, 116, 111, 111, 133, 150]

plt.figure(figsize=(20, 8), dpi=100)
print(max(time), min(time))

#设置组距
distance = 2

# 计算组数
group_num = int((max(time) - min(time)) // distance)
print(group_num)

# 第一个参数是数据,第二个参数是组数,第三个参数是范围,第四个参数是颜色,第五个参数是透明度
# 重点说一下bins参数,bins如果为10就代表将time数据分为10个等级,每个等级代表一个范围,
# 凡是time中相同范围的数据都属于一个等级,即会放在一个柱子上进行统计。
plt.hist(time, bins=group_num, range=(min(time), max(time)), color='blue', alpha=0.5)

# 修改x轴刻度标签
plt.xticks(range(min(time), max(time) + 1)[::2])
# plt.xticks(range(min(time), max(time) + 1, 2)) # 也可以用这种方式设置
plt.yticks(range(0, 20, 1), fontsize=16)
# 添加网格显示
plt.grid(linestyle="--", alpha=0.5)

# 添加x,y轴描述信息
my_font = font_manager.FontProperties(fname='C:\\Windows\\Fonts\\simsun.ttc', size=18)
plt.xlabel("电影时长", fontproperties=my_font)
plt.ylabel("电影数量", fontproperties=my_font)

plt.show()

输出结果:

156 78
39

显示结果:

六、绘制饼图

import matplotlib.pyplot as plt
from matplotlib import font_manager

label_list = ['第一部分', '第二部分', '第三部分']
size = [55, 35, 10]
color = ['red', 'green', 'blue']
explode = [0, 0.1, 0]  # 突出显示第三部分

# 绘制饼图
plt.figure(figsize=(20, 8), dpi=100)

my_font = font_manager.FontProperties(fname='C:\\Windows\\Fonts\\simsun.ttc', size=18)

# patches表示饼图的图形对象,l_text表示饼图外label的文本对象,p_text表示饼图内label的文本对象
# pie函数中的参数size表示饼图的大小,explode表示突出显示的部分,labels表示饼图的标签,colors表示饼图的颜色,autopct表示饼图内label的格式,shadow表示饼图是
# 否有阴影,startangle表示饼图的起始角度
#
patches, l_text, p_text = plt.pie(size, explode=explode, labels=label_list, colors=color,
                                  autopct='%1.1f%%', shadow=True, startangle=90,
                                  textprops={"fontproperties": my_font})

# 设置饼图外label的字体大小
for t in l_text:
    t.set_size(18)

# 设置饼图内label的字体大小
for t in p_text:
    t.set_size(16)
# p_text[0].set_color('white')  # 设置饼图内label的颜色

plt.axis('equal')  # 使得饼图为圆形,equal表示等比例
plt.legend(loc='upper right', prop=my_font)  # 设置图例位置及字体
plt.show()

显示结果:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值