# 昨日知识点回顾
安装Matplotlib
绘制简单的折线图
# 今日知识点学习
15.2.1 修改标签文字和线条粗细
# module 'backend_interagg' has no attribute 'FigureCanvas'. Did you mean: 'FigureCanvasAgg'?
# 解决办法:matplotlib切换图形界面显示终端TkAgg。
# 代码:import matplotlib
# matplotlib.use('TkAgg')
import matplotlib.pyplot as plt
import matplotlib
matplotlib.use('TkAgg')
squares = [1, 4, 9, 16, 25]
fig, ax = plt.subplots()
ax.plot(squares, linewidth=3)
# 设置图表标题并给坐标轴加上标签
ax.set_title("平方数", fontsize=24)
ax.set_xlabel("值", fontsize=14)
ax.set_ylabel("值的平方", fontsize=14)
# 设置刻度标记的大小
ax.tick_params(axis='both', labelsize=14)
plt.show()
运行结果:
如果字体为方框,解决办法参考:永久解决matplotlib 画图中文及负号显示为方框_python画图负号显示小方框-CSDN博客https://blog.csdn.net/q1148013214/article/details/81172446
解决Mac系统下matplotlib中文显示方块问题 - Ootori - 博客园 (cnblogs.com)https://www.cnblogs.com/Ootori/p/7716687.html
15.2.2 矫正图形
绘制图表发现4的平方显示为25,需要修复该问题,可向plot()函数同时提供输入输出值
# module 'backend_interagg' has no attribute 'FigureCanvas'. Did you mean: 'FigureCanvasAgg'?
# 解决办法:matplotlib切换图形界面显示终端TkAgg。
# 代码:import matplotlib
# matplotlib.use('TkAgg')
import matplotlib.pyplot as plt
import matplotlib
matplotlib.use('TkAgg')
input_values = [1, 2, 3, 4, 5]
squares = [1, 4, 9, 16, 25]
fig, ax = plt.subplots()
ax.plot(input_values, squares, linewidth=3)
# 设置图表标题并给坐标轴加上标签
ax.set_title("平方数", fontsize=24)
ax.set_xlabel("值", fontsize=14)
ax.set_ylabel("值的平方", fontsize=14)
# 设置刻度标记的大小
ax.tick_params(axis='both', labelsize=14)
plt.show()
运行结果:
15.2.3 使用内置格式
# 打开python.exe
>>> import matplotlib.pyplot as plt
>>> plt.style.available
['Solarize_Light2', '_classic_test_patch', '_mpl-gallery', '_mpl-gallery-nogrid', 'bmh', 'classic', 'dark_background', 'fast', 'fivethirtyeight', 'ggplot', 'grayscale', 'seaborn-v0_8', 'seaborn-v0_8-bright', 'seaborn-v0_8-colorblind', 'seaborn-v0_8-dark', 'seaborn-v0_8-dark-palette', 'seaborn-v0_8-darkgrid', 'seaborn-v0_8-deep', 'seaborn-v0_8-muted', 'seaborn-v0_8-notebook', 'seaborn-v0_8-paper', 'seaborn-v0_8-pastel', 'seaborn-v0_8-poster', 'seaborn-v0_8-talk', 'seaborn-v0_8-ticks', 'seaborn-v0_8-white', 'seaborn-v0_8-whitegrid', 'tableau-colorblind10']
# module 'backend_interagg' has no attribute 'FigureCanvas'. Did you mean: 'FigureCanvasAgg'?
# 解决办法:matplotlib切换图形界面显示终端TkAgg。
# 代码:import matplotlib
# matplotlib.use('TkAgg')
import matplotlib.pyplot as plt
import matplotlib
matplotlib.use('TkAgg')
# # 设置中文显示字体
# plt.rcParams['font.sans-serif']=['SimHei']
#
# # 设置正常显示符号
# plt.rcParams['axes.unicode_minus']=False
input_values = [1, 2, 3, 4, 5]
squares = [1, 4, 9, 16, 25]
plt.style.use('seaborn-v0_8')
fig, ax = plt.subplots()
ax.plot(input_values, squares, linewidth=3)
# 设置图表标题并给坐标轴加上标签
ax.set_title("平方数", fontsize=24)
ax.set_xlabel("值", fontsize=14)
ax.set_ylabel("值的平方", fontsize=14)
# 设置刻度标记的大小
ax.tick_params(axis='both', labelsize=14)
plt.show()
运行结果:(中文再次显示为方框,参考以下方法解决未果)
【环境配置】解决Matplotlib绘图时中文显示为方框的问题_如果可视化中需要用到中文,则在显示中文的时候中文呈方块状显示,思考如何解决这一-CSDN博客https://blog.csdn.net/qq_44319167/article/details/125855347