python matplotlib库笔记

编程入门 行业动态 更新时间:2024-10-23 10:22:54

python matplotlib库<a href=https://www.elefans.com/category/jswz/34/1770047.html style=笔记"/>

python matplotlib库笔记

 

matplotlib官方网站:.html

plot函数

常用的颜色:

import numpy as np
import matplotlib.pyplot as pltt=np.arange(0,4,0.1)
plt.plot(t,t,color='red',linestyle='-',marker='*',linewidth=3,label='Line1')
plt.plot(t,t**2,color='green',linestyle='--',marker='o',linewidth=1,label='Line2')
plt.legend(loc='upper left')
plt.show()

将matplotlib中的默认字体为Type-3,Type-1 和 True Type 都是矢量字体,而 Type-3 并不是(这也是为啥有时候杂志编辑要求禁止使用 Type-3 字体)

如何避免 Matplotlib 所作图中包含 Type-3 字体?

第一种方法:使用 True Type 字体。

plt.rcParams['pdf.fonttype'] = 42
plt.rcParams['ps.fonttype'] = 42

第二种方法:使用 Type-1 字体。

matplotlib.rcParams['ps.useafm'] = True
matplotlib.rcParams['pdf.use14corefonts'] = True

处理中文字体:
方法1:

x=np.arange(0,np.pi,0.01)
plt.plot(x,np.sin(x))
#只修改局部的字体
plt.xlabel('x轴',fontproperties='Times New Roman',fontsize=20)
plt.ylabel('y轴',fontproperties='Times New Roman',fontsize=20)
plt.show()

方法2:

#修改全局字体
matplotlib.rcParams['font.family']='Times New Roman'
matplotlib.rcParams['font.family']='SimHei' # 黑体,宋体:“SimSun”
matplotlib.rcParams['font.size']=20x=np.arange(0,np.pi,0.01)
plt.plot(x,np.sin(x))
plt.xlabel('x轴')
plt.ylabel('y轴')
plt.show()

使用LaTex字体:

matplotlib.rcParams['text.usetex'] = True



annotate实例(使用箭头添加注释):

x=np.arange(0,5,0.01)
plt.subplot(121)
plt.plot(x,x)
#xy为要注释的点,xytext注释文字的坐标,arrorwrops为箭头的属性
plt.annotate('x=1',xy=(3,3),xytext=(4,2.7),arrowprops=dict())
plt.subplot(122)
plt.plot(x,x)
#shrink可以使得箭头不指向点,以0.1的比例缩短箭头
plt.annotate('x=1',xy=(3,3),xytext=(4,2.7),arrowprops=dict(facecolor='black',shrink=0.1,width=2))
plt.show()

绘制扇形图:

import numpy as np
import matplotlib.pyplot as plt
import matplotliblabels=['a','b','c','d']
#百分比
sizes=[15,30,45,10]
#0.1是扇形块偏离的比例
explode=(0,0.1,0,0)
#shadow是指是否产生阴影,startangle是指开始绘制扇形图的起始角度
plt.pie(sizes,explode=explode,labels=labels,autopct='%.1f',shadow=False,startangle=90)#x轴和y轴相等,产生扇形图的平面效果
plt.axis('equal')
plt.show()


使用面向对象的方式调用绘图函数:

#subplots函数返回figure对象和2*2的axes对象(array形式)
fig,ax=plt.subplots(2,2)
ax[0,0].plot([0,1],[0,1])
ax[0,1].plot(np.arange(12),np.arange(12),marker='o')
ax[1,0].hist(np.random.randn(100),bins=50,color='k',alpha=0.5)
ax[1,1].pie([20,30,50],labels=['a','b','c'],autopct='%.1f',shadow=False)
plt.show()

import matplotlib
import matplotlib.pyplot as plt
import numpy as nplabels = ['G1', 'G2', 'G3', 'G4', 'G5']
men_means = [20, 34, 30, 35, 27]
women_means = [25, 32, 34, 20, 25]x = np.arange(len(labels))  # the label locations
width = 0.35  # the width of the barserror = np.random.rand(len(women_means))fig, ax = plt.subplots()# 在y轴方向显示误差线,error_kw中的capsize表示线的长度
rects1 = ax.bar(x - width/2, men_means, width, label='Men', yerr=error, facecolor='green', alpha=0.6, edgecolor ='k', error_kw = {'ecolor' : '0.2', 'capsize':6})
rects2 = ax.bar(x + width/2, women_means, width, label='Women',yerr=error, facecolor='red', alpha=0.6, edgecolor ='k', error_kw = {'ecolor' : '0.2', 'capsize':6})xx = []
for coord in x:xx.append(coord - width/2)xx.append(coord + width/2)yy = [40, 45,44,44,47,46,43,43,44,43]
train_std = np.random.randint(low=2, high=4, size=len(yy))
ax.plot(xx, yy, marker='o', label='Ensemble')
plt.fill_between(xx,yy - train_std,yy + train_std,alpha=0.15, color='blue')# Add some text for labels, title and custom x-axis tick labels, etc.
ax.set_ylabel('Scores')
ax.set_ylim((15, 50))
ax.set_title('Scores by group and gender')
ax.set_xticks(x)
ax.set_xticklabels(labels)
ax.legend()
ax.grid(linestyle='--', axis='y')def autolabel(rects):"""Attach a text label above each bar in *rects*, displaying its height."""for rect in rects:height = rect.get_height()ax.annotate('{}'.format(height),xy=(rect.get_x() + rect.get_width() / 2, height),xytext=(0, 6),  # 6 points vertical offsettextcoords="offset points",ha='center', va='bottom')autolabel(rects1)
autolabel(rects2)fig.tight_layout()plt.show()

绘图小技巧

import matplotlib.pyplot as plt
import numpy as np
x=np.linspace(-1,2,10)
y1=x
l1,=plt.plot(x,y1,color='r',linewidth=1,linestyle='-')#移动坐标轴
#获得图的上下左右框线
ax=plt.gca()
#上部和右部框线消失
ax.spines['right'].set_color('none')
ax.spines['top'].set_color('none')
#底部框线为x轴,左框线为y轴
ax.xaxis.set_ticks_position('bottom')
ax.yaxis.set_ticks_position('left')
#y轴移动(向左或向右)与x轴(向上或向下)相交于(0,0)点
ax.spines['bottom'].set_position(('data',0))
ax.spines['left'].set_position(('data',0))#描点(1,1)
x0=1
y0=x0
#画点(x0,y0),点大小为20
plt.scatter(x0,y0,s=20,color='b')
plt.plot([x0,x0],[y0,0],'k--',linewidth=2.5)
#xycoords='data'在xy指定的点上,xytext=(+30,-30),textcoords='offset points'相对于点的xy偏移值
plt.annotate('(%d,%d)'%(x0,y0),xy=(x0,y0),xycoords='data',xytext=(+30,-30),textcoords='offset points',fontsize=16,arrowprops=dict(arrowstyle='->',connectionstyle='arc3,rad=.2'))#在(-1,1)添加注释
plt.text(-1,1,r'$y=x$',fontdict={'size':14,'color':'y'})#设置图注
y2=2*x+1
l2,=plt.plot(x,y2,color='g')
#best是指找一个不覆盖数据的合适位置放置图注
plt.legend(handles=[l1,l2],labels=['l1','l2'],loc='best')
plt.show()

像素图的绘制并共享colorbar

import matplotlib.pyplot as plt
import numpy as np
import matplotlib# norm的作用是在设置所有子图共享的colorbar时映射的数值都在[0,1]之内
norm = matplotlib.colors.Normalize(vmin=0, vmax=1.)
#RdBu_r
fig, axs = plt.subplots(1, 2)
axs[0].imshow(np.random.random((5,5)),cmap='Blues', norm=norm)
axs[0].set_xticks([])
axs[0].set_yticks([])
ps = axs[1].imshow(np.random.random((5,5)),cmap='Blues', norm=norm)
axs[1].set_xticks([])
axs[1].set_yticks([])# 虽然colorbar设置是针对ps对象的,但是所有子图的colorbar都是一样的,
# 所以可将ps对象的colorbar作为全部的colorbar
cbar=fig.colorbar(ps, ax=axs, shrink=0.5)'''
car能调整colorbar的位置参数
# 左下宽高
cax = plt.axes([0.92, 0.27, 0.012, 0.5])
cbar=fig.colorbar(ps, ax=axs, shrink=0.5,cax=cax)
'''
cbar.set_ticks([0.0, 0.2, 0.5, 0.8, 1.])
cbar.set_ticklabels([0.0, 0.2, 0.5, 0.8, 1.])
plt.show()

import numpy as np
import matplotlib
import matplotlib.pyplot as plt
# sphinx_gallery_thumbnail_number = 2vegetables = ['1', '2', '3', '5']
farmers = ['256', '1024', '2048', '4096', '8192']harvest = np.array([[73.97, 73.99, 73.92, 73.78, 74.13],[73.79, 73.89, 74.02, 74.12, 74.26],[74.13, 74.11, 74.26, 74.31, 74.54],[73.52, 73.67, 73.86, 74.42, 74.36],])def heatmap(data, row_labels, col_labels, ax=None,cbar_kw={}, cbarlabel="", **kwargs):"""Create a heatmap from a numpy array and two lists of labels.Parameters----------dataA 2D numpy array of shape (N, M).row_labelsA list or array of length N with the labels for the rows.col_labelsA list or array of length M with the labels for the columns.axA `matplotlib.axes.Axes` instance to which the heatmap is plotted.  Ifnot provided, use current axes or create a new one.  Optional.cbar_kwA dictionary with arguments to `matplotlib.Figure.colorbar`.  Optional.cbarlabelThe label for the colorbar.  Optional.**kwargsAll other arguments are forwarded to `imshow`."""if not ax:ax = plt.gca()# Plot the heatmapim = ax.imshow(data, **kwargs)# Create colorbarcbar = ax.figure.colorbar(im, ax=ax, fraction=0.023, **cbar_kw)cbar.ax.set_ylabel(cbarlabel, rotation=-90, va="bottom")# We want to show all ticks...ax.set_xticks(np.arange(data.shape[1]))ax.set_yticks(np.arange(data.shape[0]))# ... and label them with the respective list entries.ax.set_xticklabels(col_labels)ax.set_yticklabels(row_labels)# Let the horizontal axes labeling appear on top.ax.tick_params(top=False, bottom=True,labeltop=False, labelbottom=True)# Rotate the tick labels and set their alignment.plt.setp(ax.get_xticklabels(), rotation=0, ha="center",rotation_mode="anchor")plt.setp(ax.get_yticklabels(), rotation=0, ha="right",rotation_mode="anchor")# Turn spines off and create white grid.for edge, spine in ax.spines.items():spine.set_visible(False)ax.set_xticks(np.arange(data.shape[1]+1)-.5, minor=True)ax.set_yticks(np.arange(data.shape[0]+1)-.5, minor=True)ax.set_xlabel('Number of negative instances $K_{n}$')ax.set_ylabel('Number of positive instances $K_{p}$')ax.grid(which="minor", color="w", linestyle='-', linewidth=3)ax.tick_params(which="minor", bottom=False, left=False)return im, cbardef annotate_heatmap(im, data=None, valfmt="{x:.2f}",textcolors=["black", "white"],threshold=None, **textkw):"""A function to annotate a heatmap.Parameters----------imThe AxesImage to be labeled.dataData used to annotate.  If None, the image's data is used.  Optional.valfmtThe format of the annotations inside the heatmap.  This should eitheruse the string format method, e.g. "$ {x:.2f}", or be a`matplotlib.ticker.Formatter`.  Optional.textcolorsA list or array of two color specifications.  The first is used forvalues below a threshold, the second for those above.  Optional.thresholdValue in data units according to which the colors from textcolors areapplied.  If None (the default) uses the middle of the colormap asseparation.  Optional.**kwargsAll other arguments are forwarded to each call to `text` used to createthe text labels."""if not isinstance(data, (list, np.ndarray)):data = im.get_array()# Normalize the threshold to the images color range.if threshold is not None:threshold = im.norm(threshold)else:threshold = im.norm(data.max())/2.# Set default alignment to center, but allow it to be# overwritten by textkw.kw = dict(horizontalalignment="center",verticalalignment="center")kw.update(textkw)# Get the formatter in case a string is suppliedif isinstance(valfmt, str):valfmt = matplotlib.ticker.StrMethodFormatter(valfmt)# Loop over the data and create a `Text` for each "pixel".# Change the text's color depending on the data.texts = []for i in range(data.shape[0]):for j in range(data.shape[1]):kw.update(color=textcolors[int(im.norm(data[i, j]) > threshold)])text = im.axes.text(j, i, valfmt(data[i, j], None), **kw)texts.append(text)return textsfig, ax = plt.subplots(1, 1)# YlGn
im, cbar = heatmap(harvest, vegetables, farmers, ax=ax,cmap="YlGn", cbarlabel="Top-1 accuracy (%)")
texts = annotate_heatmap(im, valfmt="{x:.2f}")#fig.tight_layout()
plt.show()

散点图的绘制

import matplotlib.pyplot as plt
import numpy as npn = 1024
# 随机生成平均值为0,方差为1的n个数
x = np.random.normal(0, 1, n)
y = np.random.normal(0, 1, n)# 对应的(x,y)点的值的大小
t = np.arctan2(x, y)
# 绘制散点图,透明度为50%
sc = plt.scatter(x, y, s=75, c=t, cmap=plt.cm.get_cmap('Blues'), alpha=0.5)
plt.colorbar(sc, fraction=0.03)  # 添加颜色渐变条, fraction可以控制长度
plt.xlim(-1.5, 1.5)
plt.ylim(-1.5, 1.5)
# 将x,y轴标签去掉
plt.xticks(())
plt.yticks(())
plt.show()

import matplotlib.pyplot as pltd = 0.1
l = 2.8
plt.plot([1.5], [4.19],marker='o')
plt.text(1.5+l, 4.19+d, 'MixNet-100', ha='center', va='bottom')
plt.plot([1.1,3.1,11.4], [18.11,16.54,15.96], marker='v', color='red')
plt.scatter([3.2,34.9, 50.9], [19.53, 17.66,16.03], marker='*', color='red')
plt.ylim([2, 21])
plt.xlabel('Parameter size (M)')
plt.ylabel('Test error rate (%) on CIFAR-10')
plt.show()

直方图与条形图的区别:

  • 条形图是用条形的长度表示各类别频数的多少,其宽度(表示类别)则是固定的;
    直方图是用面积表示各组频数的多少,矩形的高度表示每一组的频数或频率,宽度则表示各组的组距,因此其高度与宽度均有意义。
  • 由于分组数据具有连续性,直方图的各矩形通常是连续排列,而条形图则是分开排列。
  • 条形图主要用于展示分类数据,而直方图则主要用于展示数据型数据。

绘制直方图:

#bins是划分的区域个数(根据最小值和最大值的区间等分),normed是纵坐标的含义,0表示个数,1表示概率
plt.hist(np.random.normal(100,20,100),bins=10,normed=1,histtype='stepfilled',facecolor='b',alpha=0.75)
plt.show()

绘制条形图

import matplotlib.pyplot as plt
import numpy as npn=12
x=np.arange(n)
#生成0.5~1的n个数
y1=np.random.uniform(0.5,1,n)
y2=np.random.uniform(0.5,1,n)
#设置柱状图的颜色
plt.bar(x,y1,facecolor='#9999ff',edgecolor='white')
plt.bar(x,-y2,facecolor='#ff9999',edgecolor='white')#zip函数可以用于x,y1数组同时赋值
for xx,yy in zip(x,y1):#居中于条柱,top指位于条柱边缘线的下方,bottom位于条柱边缘线的上方plt.text(xx,yy,'%.2f'%yy,ha='center',va='bottom')
for xx,yy in zip(x,y2):plt.text(xx,-yy,'-%.2f'%yy,ha='center',va='top')plt.xlim(-1,12)
plt.xticks(())
plt.ylim(-1.5,1.5)
plt.yticks(())
plt.show()

import numpy as np
import matplotlib.pyplot as pltN = 6
objects = np.array([52, 49, 50, 54, 55, 58])[::-1]
scenes = np.array([65, 67, 72, 76, 85, 88])[::-1]
g1 = objects + scenes
parts = np.array([22,24,26,28,28,30])[::-1]
g2 = g1 + parts
materials = np.array([4,3,3,5,5,5])[::-1]
g3 = g2 + materials
textures = np.array([34,37,39,42,45,44])[::-1]ind = np.arange(N)    # the x locations for the groups
width = 0.8      # the width of the bars: can also be len(x) sequence
plt.figure(figsize=(8,2))
p1 = plt.barh(ind, objects, width, edgecolor ='k')
p2 = plt.barh(ind, scenes, width, left=objects, edgecolor ='k')
p3 = plt.barh(ind, parts, width, left=g1, edgecolor ='k')p4 = plt.barh(ind, materials, width, left=g2, edgecolor ='k')
p5 = plt.barh(ind, textures, width, left=g3, edgecolor ='k')
plt.yticks(rotation=45)
plt.xlabel('Number of unique detectors')
plt.yticks(ind, ('HCGNet-A', 'ResNeXt-50', 'MixNet-105', 'DPN-68', 'densenet169', 'ResNet-50'))
#plt.xticks(np.arange(0, 81, 10))
plt.legend((p1, p2, p3,p4[0],p5[0]), ('objects', 'scenes','parts','materials','textures'))
#
plt.show()

绘制等高线图

import matplotlib.pyplot as plt
import numpy as npdef f(x,y):return (1-x/2+x**5+y**3)*np.exp(-x**2-y**2)n=256
x=np.linspace(-3,3,n)
y=np.linspace(-3,3,n)
X,Y=np.meshgrid(x,y)
#填充等高线,分成10部分(0是2部分,1是3部分...),cmap指color map,每一个指=值对应颜色地图的某个值
plt.contourf(X,Y,f(X,Y),8,alpha=0.75,cmap=plt.cm.hot)
#绘制等高线,分成10部分
c=plt.contour(X,Y,f(X,Y),8,colors='k',linewidth=0.5)
#在等高线上标数据,嵌在等高线上
plt.clabel(c,inline=True,fontsize=10)
plt.show()


import numpy as np
import matplotlib.pyplot as plt
import PIL.Image as ImageN = 5
y1 = np.array([0.9576682448387146, 0.03734886646270752, 0.0023530723992735147, 0.0011507606832310557, 0.00044675703975372016])[::-1] * 100ind = np.arange(N)  # the x locations for the groups
width = 0.5  # the width of the bars: can also be len(x) sequencefig, axs = plt.subplots(1, 2)axs[0].imshow(Image.open('img2300.png'))
axs[0].set_yticks([])
axs[0].set_xticks([])
axs[0].set_title('Ground truth: ')for xx,yy in zip(ind, y1):axs[1].text(yy, xx,'%.2f'%yy+'%', ha='left', va='center')axs[1].barh(ind, y1, width, edgecolor='k')
axs[1].set_yticks(ind)
axs[1].set_yticklabels(['Crocodile', 'Table', 'Spider', 'Couch', 'Lamp'])plt.show()

绘制tsne图

matplotlib.rcParams['font.family']='Times New Roman'
matplotlib.rcParams['font.size']=30np.random.seed(1968081)net1_embeddings = np.load('embeddings1.npy') # size: (batch_size, embedding_dim)
net1_target = np.load('label1.npy') # size: (batch_size, )net2_embeddings = np.load('embeddings2.npy') # size: (batch_size, embedding_dim)
net2_target = np.load('label2.npy') # size: (batch_size, )from sklearn.model_selection import StratifiedShuffleSplit
# 从cifar-10中分层抽样部分数据
sss = StratifiedShuffleSplit(n_splits=1, test_size=0.1, random_state=1968081)
for train_index, test_index in sss.split(net1_embeddings, net1_target):train_index = np.array(train_index)net1_embeddings = net1_embeddings[train_index]net2_embeddings = net2_embeddings[train_index]net1_target = net1_target[train_index]net2_target = net2_target[train_index]target_value = list(set(net1_target))color_dict = {}
colors = ['black', 'red', 'gold', 'green', 'orange', 'blue', 'magenta', 'slategray', 'cyan', 'lightgreen']
for i, t in enumerate(target_value):color_dict[t] = colors[i]
print(color_dict)net1 = TSNE(learning_rate=1.0, perplexity=50).fit_transform(net1_embeddings)
np.save('net1.npy', net1)net2 = TSNE(learning_rate=1.0, perplexity=50).fit_transform(net2_embeddings)
np.save('net2.npy', net2)net1 = np.load('net1.npy')
net2 = np.load('net2.npy')fig, axs = plt.subplots(1, 2)scatters = []
for i in range(len(target_value)):tmp_X1 = net1[net1_target==target_value[i]]scatter1=axs[0].scatter(tmp_X1[:, 0], tmp_X1[:, 1], c=color_dict[target_value[i]], marker='v')scatters.append(scatter1)tmp_X2 = net2[net1_target == target_value[i]]scatter2 = axs[0].scatter(tmp_X2[:, 0], tmp_X2[:, 1], edgecolors=color_dict[target_value[i]], marker='h', facecolors='none')scatters.append(scatter2)axs[0].legend(scatters,('airplane', 'airplane', 'automobile', 'automobile', 'bird', 'bird', 'cat', 'cat','deer', 'deer', 'dog', 'dog', 'frog', 'frog', 'horse', 'horse','ship', 'ship', 'truck', 'truck'),scatterpoints=8,bbox_to_anchor=(0, 1),loc='lower left',ncol=10,fontsize=16)axs[0].text(-25, 22, 'Network', fontsize=20)
#axs[0].set_xticks([])
#axs[0].set_yticks([])for i in range(len(target_value)):tmp_X = net2[net1_target==target_value[i]]scatter=axs[1].scatter(tmp_X[:, 0], tmp_X[:, 1], c=color_dict[target_value[i]], marker='o')axs[1].text(13, -82, 'Recall@1=90.1')
plt.xticks([])
plt.yticks([])
plt.tight_layout()
plt.show()

更多推荐

python matplotlib库笔记

本文发布于:2024-03-09 02:34:27,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1723437.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:笔记   python   matplotlib

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!