python中的折线图

1. 案列 1
假设一天中每隔两个小时(range(2,26,2))的气温(C)分别是[15,13,14.5,17,20,25,26,26,27,22,18,15]

要求绘制出以下图像

在这里插入图片描述

from matplotlib import pyplot as plt

x = range(2, 26, 2)
y = [15, 13, 14.5, 17, 20, 25, 26, 26, 27, 22, 18, 15]
# 绘图
plt.plot(x, y) 

# 设置图片大小
plt.figure(figsize=(20, 8), dpi=80) #宽 高 像素
# 设置x轴刻度
plt.xticks(x)
# 设置y轴刻度
plt.yticks(y)
# 保存位置
plt.savefig("C:\\Users\\Administrator\\Desktop\\new.png")
plt.show()  # 所有代码效果如上图
2. 案例2
要求绘制折线图观10点到12点的每3分钟的气温变化情况 气温变化在(20,35)之间

在这里插入图片描述

from matplotlib import pyplot as plt
import random
from matplotlib import font_manager

my_font = font_manager.FontProperties(fname="C:/Windows/Fonts/simfang.ttf")  # 加载本地windows中的字体
x = range(0, 120)
y = [random.randint(20, 35) for i in range(120)]
plt.figure(figsize=(20, 8), dpi=80)  # 设置图片的大小和像素
plt.plot(x, y)
# 调整x轴的刻度
_x = list(x)[::3]  # 转换为列表,然后取步长
# 设置字符串 如103分
_x_str = ["10点{}分".format(i) for i in range(60)][::3]
_x_str += ["11点{}分".format(i) for i in range(60)][::3]
# _x_str要和_x需要对应
plt.xticks(_x, _x_str, rotation=45, fontproperties=my_font)  # rotation指定字体倾斜45度
# 添加描述信息
plt.xlabel("时间", fontproperties=my_font)
plt.ylabel("温度 单位(℃)", fontproperties=my_font)
plt.title("10点到12点的每一分钟的气温变化情况10点到12点的每3分钟的气温变化情况", fontproperties=my_font)
plt.savefig("C:\\Users\\Administrator\\Desktop\\new.png")  # 图片的保存位置
plt.show()
3. 案例3

假设老王在30岁的时候,根据自己的实际情况,统计出来了从11岁到30岁每年交的女朋友的数量如列表a,请绘制出该数据的折线图,以便分析老王每年交女朋友的数量走势

a = [1, 0, 1, 1, 2, 4, 3, 2, 3, 4, 4, 5, 6, 5, 4, 3, 3, 1, 1, 1]

在这里插入图片描述

from matplotlib import pyplot as plt
from matplotlib import font_manager

my_font = font_manager.FontProperties(fname="C:/Windows/Fonts/simfang.ttf")  # 加载本地windows中的字体
x = range(11, 31)
y = [1, 0, 1, 1, 2, 4, 3, 2, 3, 4, 4, 5, 6, 5, 4, 3, 3, 1, 1, 1]
# 设置图片的大小
plt.figure(figsize=(20, 8), dpi=80)
plt.plot(x, y, label="老王")
# 设置x轴刻度
_xtick_labels = ["{}岁".format(i) for i in x]
plt.xticks(x, _xtick_labels, fontproperties=my_font)
plt.yticks(range(0, 9))
# 绘制网格
plt.grid()
# 添加图例
plt.legend(prop=my_font, loc="upper left")
# 展示
plt.show()

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章