Matplotlib
最近一段时间在画图,学习到了一些相关的画图方法,整理在此,便于以后学习

figure 指的是画布/画板,也就是图窗的大小
axes 指的是在画布上设置一个一个的区域
- plt
# 第一种方式 画布隐式画图
plt.figure() # 定义画布
plt.plot([1,2,3],[4,5,6]) # x[1,2,3] y[4,5,6]
plt.show() # 显示画布
plt.figure() 创建一个全局绘图区域
参数:
num:设置图像编号
figsize:设置图像的宽度和高度,单位为英寸
facecolor:设置图像的背景颜色
dpi:设置绘图对象的分辨率
edgecplor:设置图像的边框颜色
- ax
# 第二种方式,区域画图
fig, ax = plt.subplots() # 定义画布 fig窗口, ax画布区域
ax.plot([1,2,3], [4,5,6]) # 通过指定ax画布区域进行画图
plt.show() # 画布显示
# 导入模块
import matploblib.pyplot as plt
import numpy as np
# 设置中文字体和负号正常显示
matplotlib.rcParams['font.sans-serif'] = ['Times New Roman'] # 字体选择
matplotlib.rcParams['axes.unicode_minus'] = False # 正常显示负号
# 产生测试数据
x = np.arange(1, 10)
y = x
fig = plt.figure() # 定义一个面板
ax1 = fig.add_subplot(111) # 定义一个坐标轴
# 设置标题
ax1.set_title('Scatter Plot')
# 设置坐标轴标签
plt.xlabel('axis') # 仅限于一个坐标关系
plt.ylabel('Y') # 仅限于一个坐标关系
# 设置坐标轴的范围
ax1.set_xlim(0, 10)
ax1.set_ylim(1, 1000)
# 设置x轴刻度显示值
ax1.set_xticks([1,2,3]) # 刻度位置
ax1.set_xticklabels(['position1', 'position2', 'position3'], rotation=30) # 刻度名称 字体旋转
ax1.tick_params(labelsize=16) # 坐标轴的字体大小
# 取消x, y轴刻度标记
ax1.xaxis.set_tick_params(size=0)
ax1.yaxis.set_tick_params(size=0)
# 设置单个边框
ax1.spines['bottom'].set_visible(False) # 取消底部边框
ax1.spines['top'].set_visible(False) # 取消顶部边框
ax1.spines['left'].set_visible(False) # 取消左部边框
ax1.spines['right'].set_visible(False) # 取消右部边框
# 查看和改变当前坐标框的位置
ax = plt.gca() # 获取当前框的图窗信息
box = ax.get_position() # 框位置信息
ax.set_position([box.x0, box.y0, box.width, box.height]) # 重新设置
# 打开网格
ax1.grid(True, linestyle=':')
# 图例
legend = ax1.legend(# loc=2, # 图例位置
bbox_to_anchor=(1, 1), # 控制图例相对于figure,这里不是axes的位置,改参数设置后loc不起作用
#ncol=2, # 图例分两行显示,当分组很多时特别有用
#fontsize=size, # 图例大小
title='instances are distinguished', # 图例标题
title_fontsize=size, # 标题字号
shadow=False, # 背景阴影
fancybox=False, # 背景框四个角为圆角
framealpha=1, ##背景框透明度
facecolor='w', # 背景框填充颜色
edgecolor='w', # 背景框颜色
# 更多参数:matplotlib.pyplot.legend
)
# 图像保存
fig.savefig('images.jpg', dpi=1200, bbox_inches='tight') # dpi分辨率, tight输出为图像紧位置
plt和ax互通
plt.axes()——fig.add_axes()
plt.subplot()——fig.add_subplot()
plt.GridSped()——fig.add_gridspec()
plt.xlabel()——axes.set_xlabel()
plt.ylabel()——axes.set_ylabel()
plt.xlim()——axes.set_xlim()
plt.ylim()——axes.set_ylim()
plt.title()——axes.set_title()
subplot的绘制
# 生成画布和axes对象
fig, ax = plt.subplots(nrow=1, ncol=2) # 生成1行两列 nrow为行,ncol为列
ax[0].plot([1,2,3],[4,5,6])
ax[1].scatter([1,2,3],[4,5,6])
各类图像绘图参考
(35条消息) 学习笔记——matplotlib学习_别呀的博客-优快云博客_plt是什么格式文件
scatter
散点形状

直方图
"""
绘制直方图
data:必选参数,绘图数据
bins:直方图的长条形数目,可选项,默认为10
normed:是否将得到的直方图向量归一化,可选项,默认为0,代表不归一化,显示频数。normed=1,表示归一化,显示频率。
facecolor:长条形的颜色
edgecolor:长条形边框的颜色
alpha:透明度
"""
plt.hist(data, bins=40, normed=0, facecolor="blue", edgecolor="black", alpha=0.7)
条形图
"""
绘制条形图
left:长条形中点横坐标
height:长条形高度
width:长条形宽度,默认值0.8
label:为后面设置legend准备
"""
rects1 = ax1.bar(left=x, height=num_list1, width=0.4, alpha=0.8, color='red', label="一部门")
bar(x, height, width=0.8, bottom=None, *, align='center', data=None, **kwargs)
水平叠加图
# 例子
import matplotlib.pyplot as plt
import matplotlib
matplotlib.rcParams['font.sans-serif'] = ['Times New Roman']
matplotlib.rcParams['axes.unicode_minus'] = False
p = plt.figure(figsize=(10, 5))
# 0
# price = [706, 623, 721, 3162, 4641]
# price1 = [276, 390, 474, 4718, 6568]
# 500
# price = [556, 665, 930, 4000, 5333]
# price1 = [279, 423, 604, 4958, 6901]
# 800
# price = [594, 674, 872, 3691, 5476]
# price1 = [292, 441, 577, 4947, 7056]
# 1000
price = [515, 810, 819, 4057, 4761]
price1 = [295, 454, 536, 4954, 7109]
# 1500
# price = [462, 752, 709, 4412, 4560]
# price1 = [256, 408, 517, 4976, 6851]
# 2000
# price1 = [300, 454, 603, 4959, 7149]
# price = [700, 653, 1105, 4028, 4974]
# 2500
# price = [744, 735, 987, 4252, 5524]
# price1 = [294, 454, 621, 5030, 7235]
# 3000
# price = [637, 742, 997, 4396, 5121]
# price1 = [306, 458, 610, 4982, 7155]
# 3500
# price = [649, 709, 1089, 4768, 5793]
# price1 = [299, 445, 617, 5020, 7307]
# 4000
# price = [708, 697, 1037, 4348, 4873]
# price1 = [290, 451, 605, 4998, 7138]
# quan
# price = [615, 660, 844, 4585, 4445]
# price1 = [297, 479, 633, 5002, 7047]
# price = [742, 742, 1307, 4295, 5143]
# price1 = [305, 463, 622, 5006, 7276]
"""
绘制水平条形图方法barh
参数一:y轴
参数二:x轴
"""
plt.barh(range(5), price, height=0.7, color='orangered', alpha=0.8, edgecolor='k', label='False Positive') # 从下往上画
# plt.barh(range(5), price, height=0.7, color='#DD7208', alpha=1, edgecolor='k',label='False Positive') # 从下往上画
plt.barh(range(5), price1, height=0.7, color='blue', alpha=0.5, edgecolor='k', label='True Positive', left=price) # 从下往上画
# plt.barh(range(5), price1, height=0.7, color='#2B684B', alpha=1, edgecolor='k', label='True Positive', left=price) # 从下往上画
plt.yticks(range(5), ['bicycle', 'motorbike', 'bus', 'person', 'car'], )
# plt.xlim(50,13200)
# plt.xlim(50,14400)
# plt.xlim(50,14700)
plt.xlim(50,13980)
# plt.xlim(50,13400)
# plt.xlim(50,14300)
# plt.xlim(50,15000)
# plt.xlim(50,14400)
# plt.xlim(50,15300)
# plt.xlim(50,13500)
# plt.xlim(50,14600)
plt.xlabel("Number of objects per class", fontsize=20)
plt.tick_params(labelsize=18)
# plt.title("不同平台图书价格")
plt.legend(
loc='lower right',
shadow=True, # 背景阴影
fancybox=True, # 背景框四个角为圆角
fontsize=18
)
num = []
for i in range(len(price)):
num.append(price[i]+price1[i])
for x, y in enumerate(num):
fp_val = price[x]
tp_val = price1[x]
fp_str_val = " " + str(fp_val)
tp_str_val = fp_str_val + " " + str(tp_val)
t = plt.text(y+100, x, tp_str_val, color='blue', va='center', fontweight='bold', fontsize=16)
plt.text(y+100, x, fp_str_val, color='orangered', va='center', fontweight='bold', fontsize=16)
ax = plt.gca()
box = ax.get_position()
ax.set_position([box.x0, box.y0+0.06, box.width, box.height])
plt.show()
# p.savefig('./faster/result800.png', dpi=400)
柱状图
# 单行
import matplotlib.pyplot as plt
import matplotlib
from brokenaxes import brokenaxes
size = 20
# 设置中文字体和负号正常显示
matplotlib.rcParams['font.sans-serif'] = ['Times New Roman']
matplotlib.rcParams['axes.unicode_minus'] = False
label_text1 = ['person','dog','bird','cat','horse','cow','sheep']
label_text2 = ['car','bicycle','motorbike','aeroplane','train','boat','bus']
label_text3 = ['chair','pottedplant','bottle','tvmonitor','sofa','diningtable']
num_list1 = [4690,510,486,376,362,259,257]
num_list2 = [1250,353,339,306,297,290,229]
num_list3 = [798,514,505,324,248,215]
# num_list1 = [330, 337, 141, 421, 287, 2008, 96]
# num_list2 = [238, 243, 181, 186, 713, 245, 261]
# num_list3 = [244, 445, 200, 245, 229, 256]
label_list = ['animal', 'vehicle', 'indoor']
x = range(len(num_list1))
"""
绘制条形图
left:长条形中点横坐标
height:长条形高度
width:长条形宽度,默认值0.8
label:为后面设置legend准备
"""
f=plt.figure(figsize=(15, 5), dpi=80)
# f, (ax1, ax2) = plt.subplots(2, 1, sharex=True)
ax1 = plt.subplot(211)
ax2 = plt.subplot(212)
# plt.figure(figsize=(15, 5), dpi=80)
# -------------------原始
rects1 = ax1.bar(x, height=num_list1, width=0.8, bottom=0, alpha=1, color=['#E86781',
'#FF5B5B', '#F771EF','#EEBBB5', '#FAC8C2','#FAC86E', '#CEC5CE']
,edgecolor=['#DD1D44','#FF3636', '#E32AE7','#E9A69E', '#FAB2A9','#E9A69E', '#B4A5B4'])
rects2 = ax1.bar([i + 8 for i in x], height=num_list2, bottom=0, alpha=1, width=0.9,
color=['saddlebrown', 'lightgrey', 'tan', 'olive', 'darkslateblue', 'firebrick', 'palevioletred']
,edgecolor=['orange','goldenrod', 'orangered','sandybrown', 'lightgreen','lightblue', 'violet'])
rects3 = ax1.bar([i + 16 for n, i in enumerate(x) if n <= 5], height=num_list3, width=0.9, bottom=0,alpha=1,
color=['wheat', 'cornflowerblue', 'mediumpurple', 'lightseagreen', 'paleturquoise', 'bisque']
,edgecolor=['orange','goldenrod', 'orangered','sandybrown', 'lightgreen','lightblue', 'violet'])
# ax1.set_ylim(0, 2600) # y轴取值范围
# ax1.set_ylabel("number of pixels")
"""
设置x轴刻度显示值
参数一:中点坐标
参数二:显示值
"""
ax2.set_xticks([3,11,18.5])
ax2.set_xticklabels(['animal', 'vehicle', 'indoor'], rotation=0)
# ax1.set_xticks([3, 11, 18.5], ['animal', 'vehicle', 'indoor'])
# ax2.set_xticks([3, 11, 18.5], label_list)
ax1.tick_params(labelsize=16)
ax2.tick_params(labelsize=16)
# plt.xlabel("年份")
# plt.title("某某公司")
# plt.legend() # 设置题注
# 编辑文本
for i, rect in enumerate(rects1):
height = rect.get_height()
ax1.text(rect.get_x() + rect.get_width() / 2, height+6, label_text1[i], ha="center", va="bottom",rotation= 90, fontsize=16)
for i, rect in enumerate(rects2):
height = rect.get_height()
ax1.text(rect.get_x() + rect.get_width() / 2, height+30, label_text2[i], ha="center", va="bottom",rotation= 90, fontsize=16)
for i, rect in enumerate(rects3):
height = rect.get_height()
ax1.text(rect.get_x() + rect.get_width() / 2, height+40, label_text3[i], ha="center", va="bottom",rotation= 90, fontsize=16)
# -------------------ax2
rects1 = ax2.bar(x, height=num_list1, width=0.8, bottom=0,alpha=1, color=['#E86781',
'#FF5B5B', '#F771EF','#EEBBB5', '#FAC8C2','#FAC86E', '#CEC5CE']
,edgecolor=['#DD1D44','#FF3636', '#E32AE7','#E9A69E', '#FAB2A9','#E9A69E', '#B4A5B4'])
rects2 = ax2.bar([i + 8 for i in x], height=num_list2, bottom=0, alpha=1, width=0.8,
color=['#6E5AB8', '#665F87', '#668A97', '#637B97', '#A76066', '#7B71C3', '#5B819B']
,edgecolor=['#4A478B', '#4A465D', '#326374', '#47607D', '#894044', '#575EB2', '#074068'])
rects3 = ax2.bar([i + 16 for n, i in enumerate(x) if n <= 5], height=num_list3, width=0.8, bottom=0,alpha=1,
color=['#888888', '#D5BDBD', '#9C9CBE', '#BB9B9B', '#BBA894', '#CEC5CE']
,edgecolor=['#767676','#C5A4A4', '#6E6EA0','#966464', '#A48B70','#B4A5B4'])
# ax2.set_ylim(0, 2600) # y轴取值范围
# ax2.set_label("number of pixels")
for i, rect in enumerate(rects1):
height = rect.get_height()
ax2.text(rect.get_x() + rect.get_width() / 2, height+40, label_text1[i], ha="center", va="bottom",rotation= 90, fontsize=16)
for i, rect in enumerate(rects2):
height = rect.get_height()
ax2.text(rect.get_x() + rect.get_width() / 2, height+40, label_text2[i], ha="center", va="bottom",rotation= 90, fontsize=16)
for i, rect in enumerate(rects3):
height = rect.get_height()
ax2.text(rect.get_x() + rect.get_width() / 2, height+40, label_text3[i], ha="center", va="bottom",rotation= 90, fontsize=16)
ax2.set_ylim(0, 1300) # outliers only
ax1.set_ylim(4600, 4770) # most of the data
# ax1.spines['bottom'].set_visible(False) # 关闭子图1中底部脊
# ax2.spines['top'].set_visible(False) ##关闭子图2中顶部脊
# ax2.set_xticks(range(0, 31, 1))
# hide the spines between ax and ax2
ax1.spines['bottom'].set_visible(False)
ax2.spines['top'].set_visible(False)
ax1.xaxis.tick_top()
ax1.set_xticks([3,11,18.5])
ax1.set_xticklabels(['','',''],rotation = 30)
ax1.tick_params(labeltop='off') # don't put tick labels at the top
ax2.tick_params(labeltop='off') # don't put tick labels at the top
ax2.xaxis.tick_bottom()
# d = .015 # how big to make the diagonal lines in axes coordinates
# # arguments to pass to plot, just so we don't keep repeating them
# kwargs = dict(transform=ax1.transAxes, color='k', clip_on=False)
# ax1.plot((-d, +d), (-d, +d), **kwargs) # top-left diagonal
# ax1.plot((1 - d, 1 + d), (-d, +d), **kwargs) # top-right diagonal
#
# kwargs.update(transform=ax2.transAxes) # switch to the bottom axes
# ax2.plot((-d, +d), (1 - d, 1 + d), **kwargs) # bottom-left diagonal
# ax2.plot((1 - d, 1 + d), (1 - d, 1 + d), **kwargs) # bottom-right diagonal
d = .65 # 设置倾斜度
# 绘制断裂处的标记
kwargs = dict(marker=[(-1, -d), (1, d)], markersize=20,
linestyle='none', color='r', mec='r', mew=1, clip_on=False)
ax1.plot([0, 1], [0, 0], transform=ax1.transAxes, **kwargs)
ax2.plot([0, 1], [1, 1], transform=ax2.transAxes, **kwargs)
plt.tight_layout()
legend = ax1.legend(# loc=2, # 图例位置
bbox_to_anchor=(1, 1), # 控制图例相对于figure,这里不是axes的位置,改参数设置后loc不起作用
#ncol=2, # 图例分两行显示,当分组很多时特别有用
#fontsize=size, # 图例大小
title='instances are distinguished', # 图例标题
title_fontsize=size, # 标题字号
shadow=False, # 背景阴影
fancybox=False, # 背景框四个角为圆角
framealpha=1, ##背景框透明度
facecolor='w', # 背景框填充颜色
edgecolor='w', # 背景框颜色
# 更多参数:matplotlib.pyplot.legend
)
plt.text(-3.2, 750, "number of object", size=size, rotation=90)
ax1.xaxis.set_tick_params(size=0)
plt.show()
f.savefig('image.jpg', dpi=400)
多行柱形图
import matplotlib.pyplot as plt
import matplotlib
import mpl_toolkits.axisartist.axislines as axislines
# 设置中文字体和负号正常显示
matplotlib.rcParams['font.sans-serif'] = ['Times New Roman']
matplotlib.rcParams['axes.unicode_minus'] = False
# label_text1 = ['bird','cat','cow','dog','horse','person','sheep']
# label_text2 = ['aeroplane','bicycle','boat','bus','car','motorbike','train']
# label_text3 = ['bottle','chair','diningtable','pottedplant','sofa','tvmonitor']
color=['#B55606', '#26697A', '#4B3B60', '#60782E', '#752E2A', '#2B4E76', 'gray']
edgecolor=['k', 'k', 'k', 'k', 'k', 'k', 'k']
num_list1 = [79.6, 79.0, 79.9, 79.9, 80.3, 80.0, 80.0]
num_list2 = [66.0, 68.2, 66.9, 68.5, 68.0, 67.8, 68.2]
num_list3 = [47.2, 47.3, 47.6, 48.3, 48.6, 47.8, 46.7]
num_list4 = [39.3, 43.1, 40.6, 42.7, 42.1, 42.7, 41.9]
num_list5 = [28.6, 30.2, 29.3, 31.4, 31.3, 31.2, 31.6]
num_list6 = [52.1, 53.6, 52.8, 54.1, 54.1, 53.9, 53.7]
num_list7 = []
for i in range(1,7):
acc = num_list6[i] - num_list6[0]
num_list7.append(acc)
num_list8 = []
for i in range(len(num_list7)):
acc = num_list7[i]/num_list6[0]
num_list8.append(acc)
print(num_list7)
print(num_list8)
x = range(len(num_list1))
x_result = range(len(num_list7))
font1 = {'family': 'Times New Roman',
'weight': 'normal',
'size': 15,
}
"""
绘制条形图
left:长条形中点横坐标
height:长条形高度
width:长条形宽度,默认值0.8
label:为后面设置legend准备
"""
f=plt.figure(figsize=(16, 7), dpi=100)
# f, (ax1, ax2) = plt.subplots(2, 1, sharex=True)
ax1 = plt.subplot(241)
ax2 = plt.subplot(242)
ax3 = plt.subplot(243)
ax4 = plt.subplot(244)
ax5 = plt.subplot(245)
ax6 = plt.subplot(246)
ax7 = plt.subplot(247)
ax8 = plt.subplot(248)
ax1.bar(x, height=num_list1, width=0.8, bottom=0, color=color, edgecolor=edgecolor)
ax1.set_ylim(76, 81)
ax1.set_xticks([])
ax1.set_xlabel('(a)', font1)
ax1.set_title('Person', fontsize=15)
ax2.bar(x, height=num_list2, width=0.8, bottom=0, color=color, edgecolor=edgecolor)
ax2.set_ylim(64, 69)
ax2.set_xticks([])
ax2.set_xlabel('(b)', font1)
ax2.set_title('Car', fontsize=15)
ax3.bar(x, height=num_list3, width=0.8, bottom=0, color=color, edgecolor=edgecolor)
ax3.set_ylim(44, 49)
ax3.set_xticks([])
ax3.set_xlabel('(c)', font1)
ax3.set_title('Bicycle', fontsize=15)
ax4.bar(x, height=num_list4, width=0.8, bottom=0, color=color, edgecolor=edgecolor)
ax4.set_ylim(38, 44)
ax4.set_xticks([])
ax4.set_xlabel('(d)', font1)
ax4.set_title('Motorbike', fontsize=15)
ax5.bar(x, height=num_list5, width=0.8, bottom=0, color=color, edgecolor=edgecolor)
ax5.set_ylim(27, 32)
ax5.set_xticks([])
ax5.set_xlabel('(e)', font1)
ax5.set_title('Bus', fontsize=15)
ax6.bar(x, height=num_list6, width=0.8, bottom=0, color=color, edgecolor=edgecolor)
ax6.set_ylim(50, 55)
ax6.set_xticks([])
ax6.set_xlabel('(f)', font1)
ax6.set_title('mAP@.5', fontsize=15)
ax7.bar(x_result, height=num_list7, width=0.8, bottom=0, color=color, edgecolor=edgecolor)
ax7.set_ylim(0, 2.5)
ax7.set_xticks([])
ax7.set_xlabel('(g)', font1)
ax7.set_title('Accuracy Improvement', fontsize=15)
ax8.bar(x_result, height=num_list8, width=0.8, bottom=0, color=color, edgecolor=edgecolor)
ax8.set_ylim(0, 0.05)
ax8.set_xticks([])
ax8.set_xlabel('(h)', font1)
ax8.set_title('Accuracy Relative Improvement', fontsize=15)
# 画线
ax1.axhline(y=num_list1[0], c="darkred", ls="--", lw=1)
ax2.axhline(y=num_list2[0], c="darkred", ls="--", lw=1)
ax3.axhline(y=num_list3[0], c="darkred", ls="--", lw=1)
ax4.axhline(y=num_list4[0], c="darkred", ls="--", lw=1)
ax5.axhline(y=num_list5[0], c="darkred", ls="--", lw=1)
ax6.axhline(y=num_list6[0], c="darkred", ls="--", lw=1)
# ax7.axhline(y=num_list6[0], c="r", ls="--", lw=1)
# ax8.axhline(y=num_list6[0], c="r", ls="--", lw=1)
ax1.axhline(y=76, c="k", ls="-", lw=1, alpha=0.5)
ax2.axhline(y=64, c="k", ls="-", lw=1, alpha=0.5)
ax3.axhline(y=44, c="k", ls="-", lw=1, alpha=0.5)
ax4.axhline(y=38, c="k", ls="-", lw=1, alpha=0.5)
ax5.axhline(y=27, c="k", ls="-", lw=1, alpha=0.5)
ax6.axhline(y=55, c="k", ls="-", lw=1, alpha=0.5)
ax7.axhline(y=0, c="k", ls="-", lw=1, alpha=0.5)
ax8.axhline(y=0, c="k", ls="-", lw=1, alpha=0.5)
# color=['orange', 'brown', 'green','blue', 'violet', 'goldenrod', 'slategray']
labels=['Original', 'FD-GAN', 'FFA-Net', 'GCA-Net', 'Grid-Net', 'MSBDN-DFF', 'PMHLD']
import matplotlib.patches as mpatches
# ax = plt.gca()
# box = ax6.get_position()
# ax.set_position([box.x0, box.y0, box.width, box.height])
patches = [mpatches.Patch(color=color[i], label="{:s}".format(labels[i]) ) for i in range(len(color)) ]
f.legend(loc='lower center', handles=patches, fontsize=15 # bbox_to_anchor=(0.5, -0.1)
, ncol=7 ,framealpha = 1 ##背景框透明度
,facecolor = 'w' # 背景框填充颜色
,edgecolor = 'w' # 背景框颜色
)
# 设置框线
ax1.spines['right'].set_visible(False)
ax1.spines['top'].set_visible(False)
ax1.spines['left'].set_visible(False)
ax1.spines['bottom'].set_visible(False)
# ax1.grid(True, linestyle=':')
ax1.grid(True,linestyle="-",linewidth=1,alpha=0.5)
ax1.set_axisbelow(True)
ax2.spines['right'].set_visible(False)
ax2.spines['top'].set_visible(False)
ax2.spines['left'].set_visible(False)
ax2.spines['bottom'].set_visible(False)
# ax2.grid(True, linestyle=':')
ax2.grid(True,linestyle="-",linewidth=1,alpha=0.5)
ax2.set_axisbelow(True)
ax3.spines['right'].set_visible(False)
ax3.spines['top'].set_visible(False)
ax3.spines['left'].set_visible(False)
ax3.spines['bottom'].set_visible(False)
# ax3.grid(True, linestyle=':')
ax3.grid(True,linestyle="-",linewidth=1,alpha=0.5)
ax3.set_axisbelow(True)
ax4.spines['right'].set_visible(False)
ax4.spines['top'].set_visible(False)
ax4.spines['left'].set_visible(False)
ax4.spines['bottom'].set_visible(False)
# ax4.grid(True, linestyle=':')
ax4.grid(True,linestyle="-",linewidth=1,alpha=0.5)
ax4.set_axisbelow(True)
ax5.spines['right'].set_visible(False)
ax5.spines['top'].set_visible(False)
ax5.spines['left'].set_visible(False)
ax5.spines['bottom'].set_visible(False)
# ax5.grid(True, linestyle=':')
ax5.grid(True, linestyle="-",linewidth=1,alpha=0.5)
ax5.set_axisbelow(True)
ax6.spines['right'].set_visible(False)
ax6.spines['top'].set_visible(False)
ax6.spines['left'].set_visible(False)
ax6.spines['bottom'].set_visible(False)
# ax6.grid(True, linestyle=':')
ax6.grid(True,linestyle="-",linewidth=1,alpha=0.5)
ax6.set_axisbelow(True)
ax7.spines['right'].set_visible(False)
ax7.spines['top'].set_visible(False)
ax7.spines['left'].set_visible(False)
ax7.spines['bottom'].set_visible(False)
# ax7.grid(True, linestyle=':')
ax7.grid(True,linestyle="-",linewidth=1,alpha=0.5)
ax7.set_axisbelow(True)
ax8.spines['right'].set_visible(False)
ax8.spines['top'].set_visible(False)
ax8.spines['left'].set_visible(False)
ax8.spines['bottom'].set_visible(False)
# ax8.grid(True, linestyle=':')
ax8.grid(True,linestyle="-",linewidth=1,alpha=0.5)
ax8.set_axisbelow(True)
# plt.setp(ax1.get_yticklabels(), visible=False)
ax1.yaxis.set_tick_params(size=0)
ax2.yaxis.set_tick_params(size=0)
ax3.yaxis.set_tick_params(size=0)
ax4.yaxis.set_tick_params(size=0)
ax5.yaxis.set_tick_params(size=0)
ax6.yaxis.set_tick_params(size=0)
ax7.yaxis.set_tick_params(size=0)
ax8.yaxis.set_tick_params(size=0)
# 平移操作
box1 = ax1.get_position()
ax1.set_position([box1.x0, box1.y0+0.01, box1.width, box1.height])
box2 = ax2.get_position()
ax2.set_position([box2.x0, box2.y0+0.01, box2.width, box2.height])
box3 = ax3.get_position()
ax3.set_position([box3.x0, box3.y0+0.01, box3.width, box3.height])
box4 = ax4.get_position()
ax4.set_position([box4.x0, box4.y0+0.01, box4.width, box4.height])
plt.show()
# f.savefig('yolov5/classes.jpg', dpi=2000, bbox_inches='tight')
折线图
import matplotlib
import matplotlib.pyplot as plt
matplotlib.rcParams['font.sans-serif'] = ['Times New Roman']
matplotlib.rcParams['axes.unicode_minus'] = False
plt.figure(figsize=(20, 8), dpi=100)
x = [0, 500, 800, 1500, 2000, 2500, 3000, 3500, 4000, 4510]
# x = [0, 500, 1000, 1500, 2000, 3500, 4000, 4510]
y1 = [56.8, 59.3, 59.3,59.5,59.4,60.0,59.4,59.7,59.7,59.8]
y2 = [32.5, 34.2, 35.3,34.0,35.4,35.9,35.5,36.0,35.4,35.9]
y3 = [44.8, 45.7, 47.9,42.9,48.2,46.8,48.6,48.3,45.9,48.0]
y4 = [34.1, 37.7, 39.3,34.8,39.9,40.7,41.1,39.9,38.6,41.4]
y5 = [18.7, 25.0, 21.9,21.8,24.1,25.8,25.2,25.5,24.5,25.6]
y6 = [37.38, 40.37, 40.75,38.61,41.36,41.85,41.94,41.87,40.84,42.14]
plt.axhline(y=39.04, c="darkred", ls="--", lw=1)
# plt.plot(x, y1, color='mediumaquamarine', marker='o', mec='mediumaquamarine', mfc='mediumaquamarine', ms=10, linestyle='--', label='person')
# plt.plot(x, y2, color='orange', marker='*', mec='orange', mfc='orange', ms=10, linestyle='--', label='car')
# plt.plot(x, y3, color='limegreen', marker='v', mec='limegreen', mfc='limegreen', ms=10, linestyle='--', label='bicycle')
# plt.plot(x, y4, color='palevioletred', marker='p', mec='palevioletred', mfc='palevioletred', ms=10, linestyle='--', label='motorbike')
# plt.plot(x, y5, color='darkturquoise', marker='h', mec='darkturquoise', mfc='darkturquoise', ms=10, linestyle='--', label='bus')
# plt.plot(x, y6, color='darkred', marker='s', mec='darkred', mfc='darkred', ms=10, label='mAP@.5')
plt.plot(x, y1, color='#2C657C', marker='o', mec='#2C657C', mfc='#2C657C', ms=10, linestyle='--', label='person')
plt.plot(x, y2, color='#607828', marker='*', mec='#607828', mfc='#607828', ms=10, linestyle='--', label='car')
plt.plot(x, y3, color='#9C9CBE', marker='v', mec='#9C9CBE', mfc='#9C9CBE', ms=10, linestyle='--', label='bicycle')
plt.plot(x, y4, color='#637B97', marker='p', mec='#637B97', mfc='#637B97', ms=10, linestyle='--', label='motorbike')
plt.plot(x, y5, color='#888888', marker='h', mec='#888888', mfc='#888888', ms=10, linestyle='--', label='bus')
plt.plot(x, y6, color='#642B28', marker='s', mec='#642B28', mfc='#642B28', ms=10, label='mAP@.5')
# plt.plot(x, y1, color='#E86781', marker='o', mec='#E86781', mfc='#E86781', ms=10, linestyle='--', label='person')
# plt.plot(x, y2, color='darkseagreen', marker='*', mec='darkseagreen', mfc='darkseagreen', ms=10, linestyle='--', label='car')
# plt.plot(x, y3, color='slategrey', marker='v', mec='slategrey', mfc='slategrey', ms=10, linestyle='--', label='bicycle')
# plt.plot(x, y4, color='#A375A3', marker='p', mec='#A375A3', mfc='#A375A3', ms=10, linestyle='--', label='motorbike')
# plt.plot(x, y5, color='#FAC86E', marker='h', mec='#FAC86E', mfc='#FAC86E', ms=10, linestyle='--', label='bus')
# plt.plot(x, y6, color='#A76066', marker='s', mec='#A76066', mfc='#A76066', ms=10, label='mAP@.5')
plt.xlabel('synthetic foggy image number', fontsize=20)
plt.ylabel('Average Precision(%)', fontsize=20)
plt.tick_params(axis='both', labelsize=16)
y1_index = y1.index(max(y1))
y2_index = y2.index(max(y2))
y3_index = y3.index(max(y3))
y4_index = y4.index(max(y4))
y5_index = y5.index(max(y5))
y6_index = y6.index(max(y6))
plt.xlim(-100, 4610)
plt.scatter(70, 40, s=3000 , color='k', marker='$Baseline$') # 在这点加个蓝色的原点 原点大小
# plt.text(x[y1_index]-1, y1[y1_index]+0.5,
# s='Max',
# fontsize=15,
# verticalalignment="top",
# horizontalalignment="right"
# )
plt.scatter(x[y1_index]-1.2, y1[y1_index]+1.2, s=500 , color='#2C657C', marker='$Max$') # 在这点加个蓝色的原点 原点大小
plt.scatter(x[y2_index], y2[y2_index]+1.2, s=500 , color='#607828', marker='$Max$') # 在这点加个蓝色的原点 原点大小
plt.scatter(x[y3_index], y3[y3_index]+1.2, s=500 , color='#9C9CBE', marker='$Max$') # 在这点加个蓝色的原点 原点大小
plt.scatter(x[y4_index], y4[y4_index]-1.2, s=500 , color='#637B97', marker='$Max$') # 在这点加个蓝色的原点 原点大小
plt.scatter(x[y5_index], y5[y5_index]+1.2, s=500 , color='#888888', marker='$Max$') # 在这点加个蓝色的原点 原点大小
plt.scatter(x[y6_index]-300, y6[y6_index]+1.2, s=500 , color='#642B28', marker='$Max$') # 在这点加个蓝色的原点 原点大小
plt.scatter(x[y6_index]-80, y6[y6_index]+1.2, s=5000 , color='#642B28', marker='$(5500, 53.43)$') # 在这点加个蓝色的原点 原点大小
plt.scatter(x[y6_index]-400, y6[y6_index]+1.2, s=100 , color='darkred', marker='^') # 在这点加个蓝色的原点 原点大小
plt.legend(loc='center', bbox_to_anchor=(0.5, 1.05), # 控制图例相对于figure,这里不是axes的位置,改参数设置后loc不起作用
#ncol=2, # 图例分两行显示,当分组很多时特别有用
fontsize=18, # 图例大小
ncol=6,
# title='instances are distinguished', # 图例标题
# title_fontsize=size, # 标题字号
shadow=False, # 背景阴影
fancybox=False, # 背景框四个角为圆角
framealpha=1, ##背景框透明度
facecolor='w', # 背景框填充颜色
edgecolor='w', # 背景框颜色
# 更多参数:matplotlib.pyplot.legend
)
# 将坐标向上提
# ax = plt.gca()
# box = ax.get_position()
# ax.set_position([box.x0, box.y0+0.08, box.width, box.height])
plt.show()
好看的颜色搭配
color=['orange', 'brown', 'green','blue', 'violet', 'goldenrod', 'slategray']
color=['#B55606', '#26697A', '#4B3B60', '#60782E', '#752E2A', '#2B4E76', 'gray']
'aliceblue': '#F0F8FF',
'antiquewhite': '#FAEBD7',
'aqua': '#00FFFF',
'aquamarine': '#7FFFD4',
'azure': '#F0FFFF',
'beige': '#F5F5DC',
'bisque': '#FFE4C4',
'black': '#000000',
'blanchedalmond': '#FFEBCD',
'blue': '#0000FF',
'blueviolet': '#8A2BE2',
'brown': '#A52A2A',
'burlywood': '#DEB887',
'cadetblue': '#5F9EA0',
'chartreuse': '#7FFF00',
'chocolate': '#D2691E',
'coral': '#FF7F50',
'cornflowerblue': '#6495ED',
'cornsilk': '#FFF8DC',
'crimson': '#DC143C',
'cyan': '#00FFFF',
'darkblue': '#00008B',
'darkcyan': '#008B8B',
'darkgoldenrod': '#B8860B',
'darkgray': '#A9A9A9',
'darkgreen': '#006400',
'darkkhaki': '#BDB76B',
'darkmagenta': '#8B008B',
'darkolivegreen': '#556B2F',
'darkorange': '#FF8C00',
'darkorchid': '#9932CC',
'darkred': '#8B0000',
'darksalmon': '#E9967A',
'darkseagreen': '#8FBC8F',
'darkslateblue': '#483D8B',
'darkslategray': '#2F4F4F',
'darkturquoise': '#00CED1',
'darkviolet': '#9400D3',
'deeppink': '#FF1493',
'deepskyblue': '#00BFFF',
'dimgray': '#696969',
'dodgerblue': '#1E90FF',
'firebrick': '#B22222',
'floralwhite': '#FFFAF0',
'forestgreen': '#228B22',
'fuchsia': '#FF00FF',
'gainsboro': '#DCDCDC',
'ghostwhite': '#F8F8FF',
'gold': '#FFD700',
'goldenrod': '#DAA520',
'gray': '#808080',
'green': '#008000',
'greenyellow': '#ADFF2F',
'honeydew': '#F0FFF0',
'hotpink': '#FF69B4',
'indianred': '#CD5C5C',
'indigo': '#4B0082',
'ivory': '#FFFFF0',
'khaki': '#F0E68C',
'lavender': '#E6E6FA',
'lavenderblush': '#FFF0F5',
'lawngreen': '#7CFC00',
'lemonchiffon': '#FFFACD',
'lightblue': '#ADD8E6',
'lightcoral': '#F08080',
'lightcyan': '#E0FFFF',
'lightgoldenrodyellow': '#FAFAD2',
'lightgreen': '#90EE90',
'lightgray': '#D3D3D3',
'lightpink': '#FFB6C1',
'lightsalmon': '#FFA07A',
'lightseagreen': '#20B2AA',
'lightskyblue': '#87CEFA',
'lightslategray': '#778899',
'lightsteelblue': '#B0C4DE',
'lightyellow': '#FFFFE0',
'lime': '#00FF00',
'limegreen': '#32CD32',
'linen': '#FAF0E6',
'magenta': '#FF00FF',
'maroon': '#800000',
'mediumaquamarine': '#66CDAA',
'mediumblue': '#0000CD',
'mediumorchid': '#BA55D3',
'mediumpurple': '#9370DB',
'mediumseagreen': '#3CB371',
'mediumslateblue': '#7B68EE',
'mediumspringgreen': '#00FA9A',
'mediumturquoise': '#48D1CC',
'mediumvioletred': '#C71585',
'midnightblue': '#191970',
'mintcream': '#F5FFFA',
'mistyrose': '#FFE4E1',
'moccasin': '#FFE4B5',
'navajowhite': '#FFDEAD',
'navy': '#000080',
'oldlace': '#FDF5E6',
'olive': '#808000',
'olivedrab': '#6B8E23',
'orange': '#FFA500',
'orangered': '#FF4500',
'orchid': '#DA70D6',
'palegoldenrod': '#EEE8AA',
'palegreen': '#98FB98',
'paleturquoise': '#AFEEEE',
'palevioletred': '#DB7093',
'papayawhip': '#FFEFD5',
'peachpuff': '#FFDAB9',
'peru': '#CD853F',
'pink': '#FFC0CB',
'plum': '#DDA0DD',
'powderblue': '#B0E0E6',
'purple': '#800080',
'red': '#FF0000',
'rosybrown': '#BC8F8F',
'royalblue': '#4169E1',
'saddlebrown': '#8B4513',
'salmon': '#FA8072',
'sandybrown': '#FAA460',
'seagreen': '#2E8B57',
'seashell': '#FFF5EE',
'sienna': '#A0522D',
'silver': '#C0C0C0',
'skyblue': '#87CEEB',
'slateblue': '#6A5ACD',
'slategray': '#708090',
'snow': '#FFFAFA',
'springgreen': '#00FF7F',
'steelblue': '#4682B4',
'tan': '#D2B48C',
'teal': '#008080',
'thistle': '#D8BFD8',
'tomato': '#FF6347',
'turquoise': '#40E0D0',
'violet': '#EE82EE',
'wheat': '#F5DEB3',
'white': '#FFFFFF',
'whitesmoke': '#F5F5F5',
'yellow': '#FFFF00',
'yellowgreen': '#9ACD32'


本文详细介绍了Matplotlib库的使用,包括figure和axes的概念,以及plt和ax的交互操作。通过示例展示了如何绘制折线图、散点图、直方图和条形图,并探讨了图像的调整、保存和颜色搭配。此外,还涵盖了子图布局、网格设置、图例和标题等高级特性,是学习和掌握Matplotlib的好资料。
5952

被折叠的 条评论
为什么被折叠?



