文章目录
前言
7月15日数据科学库学习笔记,分为三个章节:
- matplotlib 基础绘图:设置图片大小、保存、调整 x 轴和 y 轴刻度;
- 设置显示中文,包括添加 x 轴和 y 轴和图片的标题;
- 设置图形信息:定义线条样式&添加图例。
一、matplotlib 基础绘图
Python 底层绘图库,主要做数据可视化图标,模仿 MATLAB 构建。
- 示例:假设一天中每隔两个小时(range(2, 26, 2))的气温是(℃)是 [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, 24, 22, 18, 15]
plt.plot(x, y)
plt.show()
1、设置图片大小
plt.figure(figsize=(20, 8), dpi=80) # dpi 控制分辨率
2、保存
plt.savefig("./t1.png")
3、调整 x 轴和 y 轴刻度
# 设置 x 轴刻度
_xtick_labels = [i/2 for i in range(4, 49)]
plt.xticks(_xtick_labels[::3])
# 设置 y 轴刻度
plt.yticks(range(min(y), max(y)+1))
调整后的绘图如下:
二、设置显示中文
- 示例:列表 a 表示10点到12点每一分钟的气温,绘制折线图观察每分钟气温的变化情况:
1、设置显示中文
from matplotlib import font_manager
# 设置中文字体(楷体)
my_font = font_manager.FontProperties(fname=r'C:\Windows\Fonts\SIMKAI.ttf')
2、添加 x 轴和 y 轴标题
# 添加标题
plt.xlabel("时间", fontproperties=my_font)
plt.ylabel("温度/℃", fontproperties=my_font)
3、添加图片标题
plt.title("10点至12点每分钟的气温变化", fontproperties=my_font)
- 完整代码如下:
from matplotlib import pyplot as plt
import random
import matplotlib
from matplotlib import font_manager
# 设置中文字体
my_font = font_manager.FontProperties(fname=r'C:\Windows\Fonts\SIMKAI.ttf')
x = range(120)
y = [random.randint(20, 35) for i in range(120)]
plt.plot(x, y)
# 修改 x 轴刻度
_x = list(x)[::6] # 取步长,数字要和字符串一一对应
_xtick_labels = ["10点{}分".format(i) for i in range(60)]
_xtick_labels += ["11点{}分".format(i) for i in range(60)]
plt.xticks(_x, _xtick_labels[::6], rotation=45, fontproperties=my_font)
# 添加标题
plt.xlabel("时间", fontproperties=my_font)
plt.ylabel("温度/℃", fontproperties=my_font)
plt.title("10点至12点每分钟的气温变化", fontproperties=my_font)
plt.show()
三、设置图形信息
- 示例:统计你和你同桌从11岁到30岁每年交的女朋友数量如列表 a 和 b,
a = [1, 0, 1, 1, 2, 4, 3, 2, 3, 4, 4, 5, 6, 5, 4, 3, 3, 1, 1, 1]
b = [1, 0, 3, 1, 2, 2, 3, 3, 2, 1, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1]
- 请在一个图中绘制折线图:
1、定义线条样式&添加图例
# 绘制
plt.plot(x, y_1, label="自己", color="orange", linestyle=':')
plt.plot(x, y_2, label="同桌", color="cyan", linestyle='--')
# 添加图例
plt.legend(prop=my_font, loc='upper left')
- 完整代码如下:
from matplotlib import pyplot as plt
from matplotlib import font_manager
# 设置中文字体
my_font = font_manager.FontProperties(fname=r'C:\Windows\Fonts\SIMKAI.ttf')
y_1 = [1, 0, 1, 1, 2, 4, 3, 2, 3, 4, 4, 5, 6, 5, 4, 3, 3, 1, 1, 1]
y_2 = [1, 0, 3, 1, 2, 2, 3, 3, 2, 1, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1]
x = range(11, 31)
# 设置图形大小
plt.figure(figsize=(20, 8), dpi=80)
# 绘制
plt.plot(x, y_1, label="自己", color="orange", linestyle=':')
plt.plot(x, y_2, label="同桌", color="cyan", linestyle='--')
# 设置 x 轴刻度
_xtick_labels = ["{}岁".format(i) for i in x]
plt.xticks(x, _xtick_labels, fonproperties=my_font)
plt.yticks(range(9))
# 显示网格
plt.grid(alpha=0.4)
# 添加图例
plt.legend(prop=my_font, loc='upper left')
plt.show()