一、绘制一个简单图
代码如下(示例):
import matplotlib.pyplot as plt
import numpy as np
result = [] # 统计数据
max_iter_num = * # int类型
...
# 循环内
result.append((a,b,c))
...
result = np.array(result)
....
# matplotlib中文支持
plt.rcParams['font.sans-serif'] = ['SimHei'] # aaaaa.py 步骤一(替换sans-serif字体)
plt.rcParams['axes.unicode_minus'] = False # 步骤二(解决坐标轴负数的负号显示问题)
x = range(max_iter_num)
plt.plot(x,result [:,0], 'r', label='**', linestyle='-') # linestyle、marker设置线条;label线的名称
plt.plot(x,result [:,1], color='b',, label='***', marker='o')
plt.plot(x,result [:,2], 'g', label='****')
plt.legend(loc='upper left', fontsize=9) # 设置标签位置、标签字体大小,显示图例
plt.grid() # 添加网格
plt.xlabel('***') # 横轴标题
plt.ylabel('***') # 纵轴标题
plt.title('**') # 主标题
plt.show()
链接:
python画图–线条和颜色(查询):https://blog.csdn.net/alva_bobo/article/details/78087433
二、实现一张图中绘制多个子图
代码如下(示例):
import matplotlib.pyplot as plt
plt.figure()
# 坐标轴的刻度设置向内(in)或向外(out)
plt.rcParams['xtick.direction'] = 'in'
plt.rcParams['ytick.direction'] = 'in'
plt.subplot(2, 2, 1) #第一个子图
plt.xticks(fontsize=7.5) #设置刻度字体大小
plt.yticks(fontsize=7.5)
plt.title("**", fontdict={'weight': 'normal', 'size': 9}) #子图的标题内容,设置标题字体大小
plt.scatter(result[0, 1], result[0, 2], color='black')
plt.plot(result[0, 1], result[0, 0].predict(result[0, 1]), color='blue', linewidth=3)
plt.subplot(2, 2, 2) #第二个子图
plt.xticks(fontsize=7.5)
plt.yticks(fontsize=7.5)
plt.title("***", fontdict={'weight': 'normal', 'size': 9})
# plt.title("***", ..., y=-0.2) 添加‘y=-0.2’,将标题位于该图的正下方
plt.scatter(result[1, 1], result[1, 2], color='black')
plt.plot(result[1, 1], result[1, 0].predict(result[1, 1]), color='blue', linewidth=3)
plt.subplot(2, 3, 4) #第三个子图
plt.xticks(fontsize=7.5)
plt.yticks(fontsize=7.5)
plt.title("****", fontdict={'weight': 'normal', 'size': 9})
plt.scatter(result[2, 1], result[2, 2], color='black')
plt.plot(result[2, 1], result[2, 0].predict(result[2, 1]), color='blue', linewidth=3)
......
# 调整子图与子图之间的距离,hspace和wspace参数最有用
plt.subplots_adjust(hspace=0.2, wspace=0.2)
# 为给多个子图加总标题,位置在画完所有的子图后,加一句
plt.suptitle("*****", fontdict={'weight': 'normal', 'size': 20})
plt.show() # 展示
三、设置字体类型
SimHei:微软雅黑、 FangSong:仿宋、SimSun:宋体
Times New Roman:新罗马
1.设置全局英文字体为新罗马
import matplotlib.pyplot as plt
# 全局更改字体
plt.rcParams["font.family"] = "Times New Roman"
......
2.设置 fontname对整体进行修改
import matplotlib.pyplot as plt
.....
....
plt.title(Data_nameList[n], fontsize=14, fontname='Times New Roman')
....
......
3.针对legend图例设置字体(一个图中出现多个label)
使用set_fontproperties能对单个label进行修改
import matplotlib.pyplot as plt
.....
labelss = plt.legend(loc='upper right').get_texts()
[label.set_fontname('Times New Roman') for label in labelss] # 新罗马
label = labelss[0]
label.set_fontproperties('SimSun') # 宋体
plt.legend(fontsize=9) # 标签位置,字体大小
......
四、设置刻度
1.坐标轴的刻度设置向内(in)或向外(out)
import matplotlib.pyplot as plt
......
.....
plt.figure()
plt.rcParams['xtick.direction'] = 'in'
plt.rcParams['ytick.direction'] = 'in'
....
......
2.去掉上、右边框
import matplotlib.pyplot as plt
......
.....
plt.figure()
axs1 = fig.add_subplot(2, 2, 1) #2行2列第一个子图
axs1.spines['top'].set_visible(False) # 去掉上边框
axs1.spines['right'].set_visible(False) # 去掉右边框
....
......
3.双对数可视化
1>plt.loglog() 推荐
import matplotlib.pyplot as plt
......
.....
fig = plt.figure(figsize=(5.5, 5.5))
axs1 = fig.add_subplot(2, 2, i+1)
axs1.set_xlim(1, 1000)
axs1.set_ylim(0.0001, 1)
# X_dict[i], Y_dict[i] 是没有转为log10
plt.loglog(X_dict[i], Y_dict[i], '.', color='black', marker='.', markersize=4, clip_on=False)
....
......
2>该方法比较复杂,且含有小数(非整数)
import matplotlib.pyplot as plt
import matplotlib as mpl #1
......
#自行设计以10为底
def mjrFormatter(x,pos): # 4
return "$10^{{{0}}}$".format(x)
......
.....
fig = plt.figure(figsize=(5.5, 5.5))
axs1 = fig.add_subplot(2, 2, 1)
axs1.set_xlim(0, 3)
axs1.set_ylim(-4, 0)
axs1.text(0.95, 0.85, 'name', transform=axs1.transAxes, ha="right", fontdict={'weight': 'normal', 'size': 10}) # 在轴内任意位置移动title将不必要地复杂化。相反,人们宁愿在所需的位置创建一个text
axs1.xaxis.set_major_formatter(mpl.ticker.FuncFormatter(mjrFormatter)) # 2
axs1.yaxis.set_major_formatter(mpl.ticker.FuncFormatter(mjrFormatter)) # 3
# result[0, 1], result[0, 2]是转为log10
plt.scatter(result[0, 1], result[0, 2], color='black', clip_on=False, s=4) # 设置散点 s表示点的大小; clip_on=False 将点在图中显示完整
....
......
扩展学习:
1)plt.scatter(x, y, s, c ,marker, alpha) x,y: x轴与y轴的数据 s: 点的面积 c: 点的颜色 marker: 点的形状 alpha: 透明度
# 设置有边框和头部边框颜色为空right、top、bottom、left
axs1.spines['right'].set_color('none')
axs1.spines['top'].set_color('none')
plt.title("name", y=-0.1, fontdict={'weight': 'normal', 'size': 9}) # 正下方
plt.title("name", y=0.5, fontdict={'weight': 'normal', 'size': 9}) # 正中间
2) zip方法:是把2个数组糅在一起
x=[1, 2, 3, 4, 5 ]
y=[6, 7, 8, 9, 10]
zip(x, y)
就得到了[(1, 6), (2, 7), (3, 8), (4, 9), (5, 10)]
......
......
.....
X_parameter = []
Y_parameter = []
for single_square_feet, single_price_value in zip(X, Y):
X_parameter.append([float(single_square_feet)])
Y_parameter.append(float(single_price_value))
....
......