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()

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