数据分析-可视化(Matlab/Matplotlib/Seaborn)



Matlab

参考官方文档


> _ <–>https://ww2.mathworks.cn/help/matlab/ref/scatter.html

scatter

语法
scatter(x,y)
scatter(x,y,sz)
scatter(x,y,sz,c)
scatter(___,'filled')
scatter(___,mkr)
scatter(___,Name,Value)
scatter(ax,___)
s = scatter(___)
说明
示例
scatter(x,y) 在向量 x 和 y 指定的位置创建一个包含圆形的散点图。该类型的图形也称为气泡图。

示例
scatter(x,y,sz) 指定圆大小。要绘制大小相等的圆圈,请将 sz 指定为标量。要绘制大小不等的圆,请将 sz 指定为长度等于 x 和 y 的长度的向量。

示例
scatter(x,y,sz,c) 指定圆颜色。要以相同的颜色绘制所有圆圈,请将 c 指定为颜色名称或 RGB 三元数。要使用不同的颜色,请将 c 指定为向量或由 RGB 三元数组成的三列矩阵。

示例
scatter(___,'filled') 填充圆形。可以将 'filled' 选项与前面语法中的任何输入参数组合一起使用。

示例
scatter(___,mkr) 指定标记类型。

示例
scatter(___,Name,Value) 使用一个或多个名称-值对组参数修改散点图。例如,'LineWidth',2 将标记轮廓宽度设置为 2 磅。

示例
scatter(ax,___) 将在 ax 指定的坐标区中,而不是在当前坐标区中绘制图形。选项 ax 可以位于前面的语法中的任何输入参数组合之前。

示例
s = scatter(___) 返回 Scatter 对象。在创建散点图后,以后可使用 s 对其进行修改。
example:

x = linspace(0,3*pi,200);
y = cos(x) + rand(1,200);
sz = 25;
c = linspace(1,10,length(x));
scatter(x,y,sz,c,'filled')

这里写图片描述


> _ <—> https://ww2.mathworks.cn/help/matlab/ref/plot.html

plot
语法
plot(X,Y)
plot(X,Y,LineSpec)
plot(X1,Y1,...,Xn,Yn)
plot(X1,Y1,LineSpec1,...,Xn,Yn,LineSpecn)
plot(Y)
plot(Y,LineSpec)
plot(___,Name,Value)
plot(ax,___)
h = plot(___)
说明
示例
plot(X,Y) 创建 Y 中数据对 X 中对应值的二维线图。

如果 X 和 Y 都是向量,则它们的长度必须相同。plot 函数绘制 Y 对 X 的图。

如果 X 和 Y 均为矩阵,则它们的大小必须相同。plot 函数绘制 Y 的列对 X 的列的图。

如果 X 或 Y 中的一个是向量而另一个是矩阵,则矩阵的各维中必须有一维与向量的长度相等。如果矩阵的行数等于向量长度,则 plot 函数绘制矩阵中的每一列对向量的图。如果矩阵的列数等于向量长度,则该函数绘制矩阵中的每一行对向量的图。如果矩阵为方阵,则该函数绘制每一列对向量的图。

如果 X 或 Y 之一为标量,而另一个为标量或向量,则 plot 函数会绘制离散点。但是,要查看这些点,您必须指定标记符号,例如 plot(X,Y,'o')。

plot(X,Y,LineSpec) 设置线型、标记符号和颜色。

示例
plot(X1,Y1,...,Xn,Yn) 绘制多个 X、Y 对组的图,所有线条都使用相同的坐标区。

示例
plot(X1,Y1,LineSpec1,...,Xn,Yn,LineSpecn) 设置每个线条的线型、标记符号和颜色。您可以混用 X、Y、LineSpec 三元组和 X、Y 对组:例如,plot(X1,Y1,X2,Y2,LineSpec2,X3,Y3)。

示例
plot(Y) 创建 Y 中数据对每个值索引的二维线图。

如果 Y 是向量,x 轴的刻度范围是从 1 至 length(Y)。

如果 Y 是矩阵,则 plot 函数绘制 Y 中各列对其行号的图。x 轴的刻度范围是从 1 到 Y 的行数。

如果 Y 是复数,则 plot 函数绘制 Y 的虚部对 Y 的实部的图,使得 plot(Y) 等效于 plot(real(Y),imag(Y))。

plot(Y,LineSpec) 设置线型、标记符号和颜色。

示例
plot(___,Name,Value) 使用一个或多个 Name,Value 对组参数指定线条属性。有关属性列表,请参阅 Line 属性。可以将此选项与前面语法中的任何输入参数组合一起使用。名称-值对组设置将应用于绘制的所有线条。

示例
plot(ax,___) 将在由 ax 指定的坐标区中,而不是在当前坐标区 (gca) 中创建线条。选项 ax 可以位于前面的语法中的任何输入参数组合之前。

示例
h = plot(___) 返回由图形线条对象组成的列向量。在创建特定的图形线条后,可以使用 h 修改其属性。有关属性列表,请参阅 Line 属性。
example:

x = 0:pi/10:2*pi;
y1 = sin(x);
y2 = sin(x-0.25);
y3 = sin(x-0.5);

figure
plot(x,y1,'g',x,y2,'b--o',x,y3,'c*')

%--------------------------------------------

x = -pi:pi/10:pi;
y = tan(sin(x)) - sin(tan(x));

figure
plot(x,y,'--gs',...
    'LineWidth',2,...
    'MarkerSize',10,...
    'MarkerEdgeColor','b',...
    'MarkerFaceColor',[0.5,0.5,0.5])
%--------------------------------------------
ax1 = subplot(2,1,1); % top subplot
x = linspace(0,3);
y1 = sin(5*x);
plot(ax1,x,y1)
title(ax1,'Top Subplot')
ylabel(ax1,'sin(5x)')

ax2 = subplot(2,1,2); % bottom subplot
y2 = sin(15*x);
plot(ax2,x,y2)
title(ax2,'Bottom Subplot')
ylabel(ax2,'sin(15x)')

这里写图片描述

这里写图片描述
这里写图片描述


> _ <—>https://ww2.mathworks.cn/help/matlab/ref/legend.html

legend
语法
legend
legend(label1,...,labelN)
legend(labels)
legend(subset,___)
legend(target,___)
legend(___,'Location',lcn)
legend(___,'Orientation',ornt)
legend(___,Name,Value)
legend(bkgd)
lgd = legend(___)
[lgd,icons,plots,txt] = legend(___)
legend(vsbl)
legend('off')
说明
示例
legend 为每个绘制的数据序列创建一个带有描述性标签的图例。对于标签,图例使用数据序列的 DisplayName 属性中的文本。如果 DisplayName 属性为空,则图例使用 'dataN' 形式的标签。当您在坐标区上添加或删除数据序列时,图例会自动更新。此命令为 gca 返回的当前坐标区或图形创建图例。如果当前坐标区为空,则图例为空。如果坐标区不存在,此命令将创建坐标区。

示例
legend(label1,...,labelN) 设置图例标签。以字符向量或字符串列表形式指定标签,例如 legend('Jan','Feb','Mar')。

legend(labels) 使用字符向量元胞数组、字符串数组或字符矩阵设置标签,例如 legend({'Jan','Feb','Mar'})。

示例
legend(subset,___) 仅在图例中包括 subset 中列出的数据序列的项。subset 以图形对象向量的形式指定。您可以在指定标签之前或不指定其他输入参数的情况下指定 subset。

示例
legend(target,___) 使用 target 指定的坐标区、极坐标区或图形,而不是使用当前坐标区或图形。指定 target 作为第一个输入参数。

示例
legend(___,'Location',lcn) 设置图例位置。例如,'Location','northeast' 将在坐标区的右上角放置图例。请在其他输入参数之后指定位置。

示例
legend(___,'Orientation',ornt)(其中 ornt 为 'horizontal')并排显示图例项。ornt 的默认值为 'vertical',即垂直堆叠图例项。

示例
legend(___,Name,Value) 使用一个或多个名称-值对组参数来设置图例属性。设置属性时,必须使用元胞数组指定标签,例如 legend({'A','B'},'FontSize',12)。如果您不想指定标签,请包含一个空元胞数组,例如 legend({},'FontSize',12)。

示例
legend(bkgd)(其中 bkgd 为 'boxoff')删除图例背景和轮廓。bkgd 的默认值为 'boxon',即显示图例背景和轮廓。

示例
lgd = legend(___) 返回 Legend 对象。可使用 lgd 在创建图例后查询和设置图例属性。有关属性列表,请参阅 Legend 属性。

[lgd,icons,plots,txt] = legend(___) 还返回用于创建图例图标的对象、在图形中绘制的对象以及标签文本数组。不建议使用该语法。它创建的图例不支持某些功能,例如添加图例标题。此外,当您在坐标区上添加或删除数据序列时,图例不会自动更新。请改用 lgd = legend(__) 语法,以返回 Legend 对象并设置 Legend 属性。

legend(vsbl) 控制图例的可见性,其中 vsbl 为 'hide'、'show' 或 'toggle'。

示例
legend('off') 删除图例。
x = linspace(0,10);
y1 = sin(x);
plot(x,y1)
legend('First Line')

%----------------------------

y1 = rand(3);
ax1 = subplot(2,1,1); 
plot(y1)

y2 = rand(5);
ax2 = subplot(2,1,2); 
plot(y2)

legend(ax1,'Line 1','Line 2','Line 3')

%-----------------------------

x = linspace(0,3*pi);
y1 = sin(x);
p1 = plot(x,y1);

hold on
y2 = sin(x - pi/4);
p2 = plot(x,y2);

y3 = sin(x - pi/2);
p3 = plot(x,y3);
hold off

legend([p1 p3],'First','Third')

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-geCuDePP-1584501796706)(https://ww2.mathworks.cn/help/matlab/ref/addplotstoaxesaftercreatinglegendexample_01_zh_CN.png)]
这里写图片描述
这里写图片描述


> _ <—>https://ww2.mathworks.cn/help/matlab/ref/gtext.html

gtext
语法
gtext(str)
gtext(str,Name,Value)
t = gtext(___)
说明
示例
gtext(str) 在您使用鼠标选择的位置插入文本 str。当您将鼠标指针悬停在图窗窗口上时,指针变为交叉指针。gtext 将等待您选择位置。将鼠标指针移至所需位置并点击图窗或按任意键(Enter 键除外)。

gtext(str,Name,Value) 使用一个或多个名称-值对组参数指定文本属性。例如,'FontSize',14 指定 14 磅字体。

t = gtext(___) 返回由 gtext 创建的文本对象的数组。使用 t 修改所创建的文本对象的属性。有关属性和说明的列表,请参阅 Text 属性。您可以使用上述语法中的任何参数返回输出参数。
example:

clc;  
clear all;  
%y1 = (2/(1+exp(-a*u1)))-1;  
%测试不同的a值曲线的变化  
t=-10:0.2:10;  
b = 2;  
a1 = 1;  
a2 = 2;  
a3 = 3;  
a4 = 4;  
a5 = 5;  
y1 = (b./(1+exp(-a1*t)))-1;%一个数除以矩阵  
y2 = (b./(1+exp(-a2*t)))-1;  
y3 = (b./(1+exp(-a3*t)))-1;  
y4 = (b./(1+exp(-a4*t)))-1;  
y5 = (b./(1+exp(-a5*t)))-1;  
%绘制不同的a值得曲线变化  
figure(1)  
plot(t,y1,'r',t,y2,'--b',t,y3,'g',t,y4,'y',t,y5,'k','linewidth',0.5);  
hold on;  
grid on;  
legend('a=1','a=2','a=3','a=4','a=5','fontsize',5);  
% xlabel('矢量号','fontsize',18);  
% ylabel('ID电流/A','fontsize',18);  
% xlim([1, aa]);  
% ylim([1, 2.5]);  
title('a值不同的sigmoid曲线')  
gtext(' \leftarrow a=1');  
gtext(' \leftarrow a=2');  
gtext(' \leftarrow a=3');  
gtext(' \leftarrow a=4');  
gtext(' \leftarrow a=5');  

这里写图片描述

% close all;
% load('图5a.mat')
% x_axisd=single(x_axis)
% y_axisd=single(y_axis)
% %Plot this data as a bar chart
% h=figure; hold;
% %bar(x_axisd,y_axisd)
% %bar(x_axisd,y_axisd,'FaceColor',[52/255 148/255 1],'EdgeColor',[1 1 1],'LineWidth',1.0)
% bar(x_axisd,y_axisd,'FaceColor',[51/255 102/255 1],'EdgeColor',[1 1 1],'LineWidth',0.5)
% %barmap=[51/255 153/255 1]; %[0.7 0.7 0.7] is grey, [ 0.05 .45 0.1] is green
% %colormap(barmap)
% xlabel('age class','FontSize',14)
% ylabel('num','FontSize',14)
% title('megage age distribution','FontSize',14)
% %title('adience age distribution','FontSize',14)
% legend('age distribution')
% saveas(h, '图5a.fig','fig')
% pause; 
% close all;

% close all;
% x=[-10:0.01:10]%定义自变量的取值  
% y=1./(1+exp(-x))%sigmoid函数 函数里一定要用点除‘./’,因为是矩阵运算,所以要把纬度保持一致。  
% h=figure; 
% plot(x,y); %绘制图形  
% hold on;  
% grid on; 
% set(gca,'YTick',0:0.2:1);
% % set(gca,'XTick',-15:5:15);
% % set(gca,'XTickLabel',{'-pi','-pi/2','0','pi/2','pi'});
% xlabel('Age Difference','fontsize',18)%添加横轴名称  
% ylabel('P(A younger than B)','fontsize',18)%添加纵轴名称  
% % legend('sigmoid')%添加曲线标记符  
% % title('sigmoid')%给图像添加标题  
% % gtext(' \leftarrow a=1');  
% for k = 1:17
%     gtext('\fontsize{20} \color[rgb]{0,0.5,0.5} \circ');  
%     % gtext('\otimes');
% end
% saveas(h, '图3.fig','fig')
% pause; 
% close all;


% close all;
% load('图6c1.mat')
% x=[1:1:500]%定义自变量的取值  
% h=figure; 
% plot(x,tr_acc,'b',x,tr_diag,'r',x,te_acc,'c',x,te_diag,'g','linewidth',1);  
% hold on;   
% legend('train acc','train 1off','test acc','test 1off','fontsize',5,'Location','southeast'); 
% xlabel('count','fontsize',14)%添加横轴名称  
% ylabel('acc/1off','fontsize',14)%添加纵轴名称   
% % title('sigmoid')%给图像添加标题  
% % xlim([1, aa]);  
% % ylim([1, 2.5]);  
% title('acc/1off','fontsize',14)
% 
% saveas(h, '图6c1.fig','fig')
% pause; 
% close all;

% close all;
% %load('图6c2.mat')
% x=[1:1:500]%定义自变量的取值  
% h=figure; 
% plot(x,tr_loss,'b',x,te_loss,'r','linewidth',1);  
% hold on;   
% legend('train center loss','test center loss','fontsize',5,'Location','northeast'); 
% xlabel('count','fontsize',14)%添加横轴名称  
% ylabel('center loss','fontsize',14)%添加纵轴名称   
% % title('sigmoid')%给图像添加标题  
% % xlim([1, aa]);  
% % ylim([1, 2.5]);  
% title('center loss','fontsize',14)
% 
% saveas(h, '图6c2.fig','fig')
% pause; 
% close all;

close all;
load('图7d.mat')
sz=20;%指定圆大小。要绘制大小相等的圆圈,请将 sz 指定为标量。要绘制大小不等的圆,请将 sz 指定为长度等于 x 和 y 的长度的向量。
h=figure; 
scatter(embeds(:,1),embeds(:,2),sz,labels,'filled');
hold on;   
xlabel('x','fontsize',14)%添加横轴名称  
ylabel('y','fontsize',14)%添加纵轴名称    
title('feature distribution','fontsize',14)
gtext('\fontsize{15} \color[rgb]{0,0,0} 0'); 
gtext('\fontsize{15} \color[rgb]{0,0,0} 1'); 
gtext('\fontsize{15} \color[rgb]{0,0,0} 2'); 
gtext('\fontsize{15} \color[rgb]{0,0,0} 3'); 
gtext('\fontsize{15} \color[rgb]{0,0,0} 4'); 
gtext('\fontsize{15} \color[rgb]{0,0,0} 5'); 
gtext('\fontsize{15} \color[rgb]{0,0,0} 6'); 
gtext('\fontsize{15} \color[rgb]{0,0,0} 7'); 

saveas(h, '图7d.fig','fig')
pause; 
close all;


Matplotlib

如果title是中文,matplotlib会乱码,这时需要加上下面这段代码:
plt.rcParams['font.sans-serif']=['SimHei']
如果需要将数字设为负数,也可能出现乱码的情况,这时候可以加下面的代码:
plt.rcParams['axes.unicode_minus']=False

  • 添加注释
    有时候我们需要对特定的点进行标注,我们可以使用 plt.annotate 函数来实现:
    s: 注释信息内容
    xy:箭头点所在的坐标位置
    xytext:注释内容的坐标位置
    arrowprops:设置指向箭头的参数
x=np.linspace(0,10,200)#从0到10之间等距产生200个值
y=np.sin(x)

plt.plot(x,y,linestyle=':',color='b')
plt.annotate(s='标记点',xy=(3,np.sin(3)),xytext=(4,-0.5),weight='bold',color='b',\arrowprops=dict(arrowstyle='-|>',color='k'))
plt.show()
  • Figure对象
    在matplotlib中,整个图像为一个Figure对象。在Figure对象中可以包含一个或者多个Axes对象。每个Axes(ax)对象都是一个拥有自己坐标系统的绘图区域。
plt.figure(figsize=(6, 3))
plt.plot(6, 3)
plt.plot(3, 3 * 2)
# 坐标轴及标签
plt.xlim(0,6) #x轴坐标轴
plt.ylim((0, 3))#y轴坐标轴
plt.xlabel('X')#x轴标签
plt.ylabel('Y')#y轴标签
# 设置label和legend
plt.plot(2, 3, label="123")#第一个label
plt.plot(2, 3* 2, label="456")#第二个label
plt.legend(loc='best')#图列位置,可选best,center等
plt.show()

使用子图
如果需要将多张子图展示在一起,可以使用 subplot() 实现。即在调用 plot()函数之前需要先调用 subplot() 函数。该函数的第一个参数代表子图的总行数,第二个参数代表子图的总列数,第三个参数代表活跃区域。

ax1 = plt.subplot(2, 2, 1)
plt.plot(x,np.sin(x), 'k')

ax2 = plt.subplot(2, 2, 2, sharey=ax1) # 与 ax1 共享y轴
plt.plot(x, np.cos(x), 'g')

ax3 = plt.subplot(2, 2, 3)
plt.plot(x,x, 'r')

ax4 = plt.subplot(2, 2, 4, sharey=ax3) # 与 ax3 共享y轴
plt.plot(x, 2*x, 'y')

在这里插入图片描述


scatter
# 绘制散点图,主要用到plt.scatter()这个函数。
# x,y是必填参数;
# c(颜色:b--blue, c--cyan,g--green,k--black,m--magenta,r--red,w--white,y--yellow);
# s:控制点的大小,默认为20);
# marker:指定散点图点的形状,默认为圆形;
# alpha:指定对象的透明度;
# 绘制简单的散点图:
x = np.random.rand(10)
y = np.random.rand(10)
plt.scatter(x,y)
plt.show()

进行简单的一些参数设置:

x = np.random.rand(50)
y = np.random.rand(50)
colors = np.random.rand(50)
s = (30 * np.random.rand(n))**2
plt.scatter(x, y,s, c=colors, alpha=0.5)
plt.show()

在这里插入图片描述
散点矩阵图scatter_matrix,diagonal = ''为每个指标的频率图,有kde及hist两个参数可选;range_padding 是图像在x轴,y轴原点附近的留白,值越大,图像离坐标原点的距离越大。
df = pd.DataFrame(np.random.randn(100, 4), columns = list(‘abcd’))
pd.scatter_matrix(df, figsize = (8,6),marker = ‘o’,diagonal = ‘kde’,alpha = 0.4,range_padding = 0.05)
在这里插入图片描述


plot
plt.subplots(figsize=(7,5.5));
plt.plot(roc[:,0], roc[:,2]/100., color='darkorange', lw=2, label='clear recoll');
plt.plot(roc[:,0], roc[:,3]/100., color='b', lw=2, label='blur recoll');
plt.xlim([0.0, 1.0]);
plt.ylim([0.0, 1.0]);
new_ticks = np.linspace(0,1,11)
plt.xticks(new_ticks)
plt.yticks(new_ticks)
plt.xlabel('Threshhold');
plt.ylabel('recoll rate');
plt.title('x208-Test#5');
plt.legend(loc="lower right");
plt.grid(True)
plt.show()

在这里插入图片描述

from sklearn.metrics import auc
P,r0,r1,threshold = roc[:,1]/100.,roc[:,2]/100.,roc[:,3]/100.,roc[:,0]
AUC = auc(r0,r1) ###计算auc的值

plt.scatter(x=r0,y=r1,label='(clear recoll,blur recoll)',color='darkorange')
# plt.plot(r0, r1, 'r',label='AUC')
plt.plot(r0, r1, 'r')

# plt.scatter(x=P,y=r1,label='(p,recall1)',color='g')
# plt.plot(P, r1, 'seagreen',label='AUC')

plt.legend(loc='lower right')

plt.title('x208-Test#5')
plt.xlim([0,1.])
plt.ylim([0,1.])
new_ticks = np.linspace(0,1,11)
plt.xticks(new_ticks)
plt.yticks(new_ticks)
plt.ylabel('blur recoll')
plt.xlabel('clear recoll')
plt.grid(True)
plt.show()

在这里插入图片描述


bar
fig, ax = plt.subplots()
str1='0.1', '0.2', '0.3', '0.4', '0.5', '0.6', '0.7', '0.8', '0.9', '1.0'
ax.bar(range(10), iou_th, 0.5, label="IOU Distribution", tick_label=str1)
ax.legend(loc=0); # upper left corner
ax.set_xlabel('IOU Threshold')
ax.set_ylabel('Number')
ax.set_xticks(range(10))
#ax.set_title('IRdataset gender distribution');
# plt.xticks(cls_attr1)
# plt.xticks(cls_attr1[ind], cls_attr2[ind])
#fig.savefig("plot_gym/megaage_asian_allage100class.png") 
plt.show()

在这里插入图片描述

# no.2
N = 50
preMeans = pp
gtMeans = ll
preStd = None
gtStd = None
ind = np.arange(N)    # the x locations for the groups
width = 0.35       # the width of the bars: can also be len(x) sequence

p1 = plt.bar(ind, preMeans, width, yerr=preStd)
p2 = plt.bar(ind, gtMeans, width,
             bottom=preMeans, yerr=gtStd)

plt.xlabel('Test sample')
plt.ylabel('Depression Scores')
plt.title('AVEC 13')
#plt.xticks(ind, ('G1', 'G2', 'G3', 'G4', 'G5'))
plt.yticks(np.arange(0, 81, 10))
plt.legend((p1[0], p2[0]), ('Prediction', 'Ground truth'))

plt.show()

在这里插入图片描述

# plt no.1:
n_groups = 10

means_pre = blur_x203vvv
std_pre = None

means_gt = blur_x205vvv
std_gt = None

means_gt2 = blur_x206vvv
std_gt2 = None

means_gt3 = blur_x207vvv
std_gt3 = None

fig, ax = plt.subplots()

index = np.arange(n_groups)
bar_width = 0.2

opacity = 0.4
error_config = {'ecolor': '0.4'}

rects1 = ax.bar(index, means_pre, bar_width,
                alpha=opacity, color='b',
                yerr=std_pre, error_kw=error_config,
                label=label1_name)

rects2 = ax.bar(index + bar_width, means_gt, bar_width,
                alpha=opacity, color='r',
                yerr=std_gt, error_kw=error_config,
                label=label2_name)

rects3 = ax.bar(index + bar_width*2, means_gt2, bar_width,
                alpha=opacity, color='g',
                yerr=std_gt2, error_kw=error_config,
                label=label3_name)

rects4 = ax.bar(index + bar_width*3, means_gt3, bar_width,
                alpha=opacity, color='c',
                yerr=std_gt3, error_kw=error_config,
                label=label4_name)

ax.set_xlabel('score distribution')
ax.set_ylabel('sample numbers')
ax.set_title(table_name)
ax.grid(True)
ax.legend()

fig.tight_layout()
plt.show()

在这里插入图片描述
水平向的条形图调用的是barh():

# 水平向
df.plot.barh( grid = True, colormap = 'BuGn_r')

在这里插入图片描述
与垂直柱状图一样,如果想要柱状图实现堆叠效果,则加上:stacked=true
在这里插入图片描述


pie
plt.pie(x, explode=None, labels=None, colors=None, autopct=None, pctdistance=0.6, shadow=False, 
          labeldistance=1.1, startangle=None, radius=None, counterclock=True, wedgeprops=None, 
          textprops=None, center=(0, 0), frame=False)

常用参数及说明:
在这里插入图片描述
'%1.1f'指小数点前后位数(没有用空格补齐),

import matplotlib.pyplot as plt

# Pie chart, where the slices will be ordered and plotted counter-clockwise:
labels = '0.1', '0.2', '0.3', '0.4', '0.5', '0.6', '0.7', '0.8', '0.9', '1.0'
sizes = iou_th
explode = (0.1, 0, 0, 0, 0, 0, 0, 0, 0, 0)  # only "explode" the 2nd slice (i.e. 'Hogs')

fig1, ax1 = plt.subplots(figsize=(7, 7))
ax1.pie(sizes, explode=explode, labels=labels, autopct='%1.1f%%',
        shadow=True, startangle=90)
ax1.axis('equal')  # Equal aspect ratio ensures that pie is drawn as a circle.

plt.show()

在这里插入图片描述

import numpy as np
import matplotlib
from matplotlib import pyplot as plt
# matplotlib.rcParams['font.sans-serif']='Microsoft Yahei' #改字体为微软雅黑,以便显示中文
fig,ax=plt.subplots()

animal={"0.1":iou_th[0],"0.2":iou_th[1],"0.3":iou_th[2],"0.4":iou_th[3],"0.5":iou_th[4],"0.6":iou_th[5],"0.7":iou_th[6],"0.8":iou_th[7],"0.9":iou_th[8],"1.0":iou_th[9]} #创建数据
data=np.array([i for i in animal.values()]).astype(float) #饼图显示数据,将其转换成float格式
label=np.array([j for j in animal.keys()]) #设置标签
ax.pie(data,labels=label,autopct='%.1f%%',startangle=90,counterclock=False,wedgeprops=dict(width=0.6,edgecolor='w')) #autopct为显示百分比,startangle为起始角度,counterclock逆时针选否
ax.set_title("IOU Distribution") #设置标题
ax.axis("equal") #设置x轴和y轴等长,否则饼图将不是一个正圆

plt.show()

在这里插入图片描述

from matplotlib import font_manager as fm
import matplotlib as mpl

# Pie chart, where the slices will be ordered and plotted counter-clockwise:
labels = ['0.1', '0.2', '0.3', '0.4', '0.5', '0.6', '0.7', '0.8', '0.9', '1.0']
sizes = iou_th
explode = [0.1] + [0 for i in range(9)]  # only "explode" the 1st slice

fig, axes = plt.subplots(figsize=(12,7),ncols=2) # 设置绘图区域大小
ax1, ax2 = axes.ravel()

# colors = cm.rainbow(np.arange(len(sizes))/len(sizes)) # colormaps: Paired, autumn, rainbow, gray,spring,Darks
patches, texts, autotexts = ax1.pie(sizes, labels=labels, autopct='%1.0f%%', explode=explode,
        shadow=False, startangle=170)#, colors=colors)

ax1.axis('equal')  

# 重新设置字体大小
proptease = fm.FontProperties()
proptease.set_size('large')
# font size include: ‘xx-small’,x-small’,'small’,'medium’,‘large’,‘x-large’,‘xx-large’ or number, e.g. '12'
plt.setp(autotexts, fontproperties=proptease)
plt.setp(texts, fontproperties=proptease)

ax1.set_title('IOU Distribution', loc='center')

# ax2 只显示图例(legend)
ax2.axis('off')
ax2.legend(patches, labels, loc='center left')

plt.tight_layout()
# plt.savefig('Demo_project_set_legend_good.jpg')
plt.show()

在这里插入图片描述

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
 
datafile = ''
data = pd.read_excel(datafile)
x1 = data[data['时间']==2005].iloc[:,1:].values.tolist()[0]#多重饼图第一层数据
x2 = data[data['时间']==2010].iloc[:,1:].values.tolist()[0]#多重饼图第二层数据
 
fig,ax = plt.subplots()
colors = ['hotpink','slateblue','goldenrod','olivedrab']
labels = 'Jay income','JJ income','Jolin income','Hannah income'#图例
pie_1 = ax.pie(x1,startangle=90,autopct='%1.1f%%',radius=1.5,pctdistance = 0.9,colors=colors, labels=labels)
pie_2 = ax.pie(x2,startangle=90,autopct='%1.1f%%',radius=1.2,pctdistance = 0.6,colors=colors)
 
#添加多重饼图的分割线
for pie_wedge in pie_1[0]:
    pie_wedge.set_edgecolor('black')
for pie_wedge in pie_2[0]:
    pie_wedge.set_edgecolor('black')
 
ax.set(aspect="equal")
plt.show()#显示图表

在这里插入图片描述


直方图hist
直方图绘制为hist()函数,参数如下:
data:必选参数,绘图数据
bins:直方图的长条形数目,可选项,默认为10
normed:是否将得到的直方图向量归一化,可选项,默认为0,代表不归一化,显示频数。normed=1,表示归一化,显示频率。
facecolor:长条形的颜色
edgecolor:长条形边框的颜色
alpha:透明度
s = pd.Series(np.random.randn(1000))
s.hist(bins = 20,histtype = 'bar',align = 'mid',orientation = 'vertical',alpha = 0.5,normed = True)

在这里插入图片描述
密度图,加上:
s.plot(kind = 'kde', style = 'k--')
在这里插入图片描述


polar 极坐标图

matplotlib的pyplot子库提供了绘制极坐标图的方法。在调用subplot()创建子图时通过设置projection=‘polar’,便可创建一个极坐标子图,然后调用plot()在极坐标子图中绘图。

部分参数意义:
theta:角度数据
radii :极径数据
theta_direction方法用于设置极坐标的正方向
theta_zero_location方法用于设置极坐标0°位置,0°可设置在八个位置,分别为N, NW, W, SW, S, SE, E, NE
thetagrids方法用于设置极坐标角度网格线显示
theta_offset方法用于设置角度偏离

极区图:

N = 20
theta = np.linspace(0, 2 * np.pi, N, endpoint = False)
radii = 10 * np.random.rand(N)
width = np.pi / 4 * np.random.rand(N)

ax = plt.subplot(111, projection = 'polar')
bars = ax.bar(theta, radii, width = width, bottom = 0.0)

在这里插入图片描述
极散点图:

theta = np.arange(0,2*np.pi, np.pi/4) # 数据角度
r = np.arange(1,9,1) #数据极径
area = 100*np.arange(1,9,1) # 数据散点面积
colors = theta
ax2 = plt.subplot(111,projection='polar')
ax2.scatter(theta, r, c=colors, s=area, cmap='hsv', alpha =0.75)

在这里插入图片描述


boxplot 箱型图

绘制箱线图,用plt.boxplot()这个函数。箱型图是利用数据中的五个统计量:最小值、第一四分位数、中位数、第三四分位数与最大值来描述数据的一种方法。它也可以粗略地看出数据是否具有有对称性,分布的分散程度等信息,特别可以用于对几个样本的比较。
在这里插入图片描述

生成单个箱型图:
np.random.seed(100)#生成随机数
data=np.random.normal(size=1000,loc=0,scale=1)
plt.boxplot(data,sym='o',whis=1.5)
plt.show()

在这里插入图片描述
多个箱型图:
箱型图也可以是横向的,加上vert=False即可

np.random.seed(100)#生成随机数
data=np.random.normal(size=(1000,4),loc=0,scale=1) #1000个值得4维数组
lables = ['A','B','C','D']
plt.boxplot(data,labels=lables)
plt.show()

在这里插入图片描述


Seaborn 图形可视化

https://zhuanlan.zhihu.com/p/28447106.
https://zhuanlan.zhihu.com/p/45237245.
https://blog.csdn.net/sunchengquan/article/details/78573244.

显示中文
Seaborn 对中文的显示不太友好,如果在遇到乱码问题时,可以加入下面的代码。
# 指定默认字体
mpl.rcParams['font.sans-serif'] = ['SimHei']  

# 解决保存图像是负号'-'显示为方块的问题 
mpl.rcParams['axes.unicode_minus'] = False  
保存图片
画出的图形我们需要保存,可以先建立一个画布,设置我们图像的大小,然后将这个画布保存下来。
#设置一个(12,6)的画布
plt.figure(figsize=(12, 6))

#图形绘制代码
sns.boxplot(data=data,palette=sns.color_palette('Blues')) 

#将画布保存为'xiang.png',还可以保存为jpg、svg格式图片
plt.savefig('xiang.png')

distplot 直方图

distplot() 默认拟合出了密度曲线,可以看出分布的变化规律。
通常我们在分析一组数据时,首先要看的就是变量的分布规律,而直方图则提供了简单快速的方式,在 Seaborn 中可以用 distplot() 实现。

我们首先导入数据集 ‘titanic’,并查看随机的10行数据,对数据集有一个初步的印象:

import matplotlib.pyplot as plt
import seaborn as sns
%matplotlib inline
#导数数据集'titanic'
titanic=sns.load_dataset('titanic')
#查看数据集的随机10行数据,用sample方法
titanic.sample(10)
#去除'age'中的缺失值,distplot不能处理缺失数据
age1=titanic['age'].dropna()
sns.distplot(age1)

在这里插入图片描述

同时我们可以调节其中的一些参数,来控制输出的图形。
'kde' 是控制密度估计曲线的参数,默认为 True,不设置会默认显示,如果我们将其设为 False,则不显示密度曲线。
#去掉拟合的密度估计曲线,kde参数设为False
# 'bins'是控制分布矩形数量的参数,通常我们可以增加其数量,来看到更为丰富的信息。
# 通过'bins'参数设定数据片段的数量
sns.distplot(age1,bins=30,kde=False)

在这里插入图片描述
'reg' 参数用于控制直方图中的边际毛毯,通过控制'reg'是实现毛毯是否显示。

#创建一个一行2列的画布,主要方便对比
fig,axes=plt.subplots(1,2)

#设置'reg'参数,加上观测数值的边际毛毯
#需要用axes[]表示是第几张图,从0开始
sns.distplot(age1,ax=axes[0]) #左图
sns.distplot(age1,rug=True,ax=axes[1]) #右图

在这里插入图片描述

当然,除了控制矩形分布、密度曲线及边际毛毯是否显示,还可以通过更丰富的参数控制他们展示的细节,
这些通过参数 'hist_kws' 、'kde_kws' 、'reg_kws' 来进行设置,因为其中涉及到多个参数,参数间用逗号隔开,
参数外面用大括号括住。
#可以分别控制直方图、密度图的关键参数
fig,axes=plt.subplots(1,2) 
sns.distplot(age1,rug=True,ax=axes[0])
sns.distplot(age1,rug=True,
                     hist_kws={'color':'green','label':'hist'},
                     kde_kws={'color':'red','label':'KDE'},
                     ax=axes[1])

在这里插入图片描述


barplot 条形图

barplot() 利用矩阵条的高度反映数值变量的集中趋势,以及使用errorbar功能(差棒图)来估计变量之间的差值统计(置信区间)。需要提醒的是 barplot() 默认展示的是某种变量分布的平均值(可通过参数修改为 max、median 等)。

这里我们仍然以’titanic’数据集作为展示,将’class’设为x轴,'survived’设为y轴。

import seaborn as sns
import matplotlib.pyplot as plt
%matplotlib inline

#导入数据集'titanic',命名为'titanic'
titanic=sns.load_dataset('titanic')

#将'class'设为x轴,'survived'为y轴,传入'titanic'数据
sns.barplot(x='class',y='survived',data=titanic)

我们可以通过设置’hue’参数,对x轴的数据进行细分,细分的条件就是’hue’的参数值,比如这里我们的x轴是’class’(仓位等级),我们将其按’sex’(性别)再进行细分。
sns.barplot(x='class',y='survived',hue='sex',data=titanic)
在这里插入图片描述


countplot 计数图

由此可见,我们选定某个字段,countplot() 会自动帮我们统计该字段下各类别的数目。当然,我们也可以再传入’hue’参数,进行细分,这里我们加入’sex’分类。

import seaborn as sns
import matplotlib.pyplot as plt
%matplotlib inline
titanic=sns.load_dataset('titanic')

#sns.countplot(x='deck',data=titanic)
sns.countplot(x='deck',hue='sex',data=titanic)

如果我们希望调换横纵坐标,也就是类别放于纵坐标,计数值横坐标显示,将x轴换为y轴即可。
sns.countplot(y='deck',hue='who',data=titanic)
在这里插入图片描述


stripplot/swarmplot 散点图

在seaborn中有两种不同的分类散点图。stripplot() 使用的方法是用少量的随机“抖动”调整分类轴上的点的位置,swarmplot() 表示的是带分布属性的散点图。

import seaborn as sns
import matplotlib.pyplot as plt
%matplotlib inline
titanic=sns.load_dataset('titanic')

sns.stripplot(x='embarked',y='fare',data=titanic)

在这里插入图片描述
这里我们可以通过设置'jitter'参数控制抖动的大小。
sns.stripplot(x='embarked',y='fare', data=titanic,jitter=1)

在这里插入图片描述
swarmplot() 方法使用防止它们重叠的算法沿着分类轴调整点。它可以更好地表示观测的分布,它适用于相对较小的数据集。
sns.swarmplot(x='embarked',y='fare',data=titanic)
在这里插入图片描述
可以通过’hue’参数,对散点图添加更多细分的维度,Seaborn 中会以颜色来进行区分。
sns.swarmplot(x='embarked',y='age',hue='who',data=titanic)
在这里插入图片描述


boxplot 箱线图

boxplot(箱线图)是一种用作显示一组数据分散情况的统计图。它能显示出一组数据的最大值、最小值、中位数及上下四分位数。因形状如箱子而得名。这意味着箱线图中的每个值对应于数据中的实际观察值。
在这里插入图片描述

# 以'titanic'数据集为例,我们首先来探索不同的'class'(船舱)下的乘客的'age'(年龄)情况。
# 同样的,可以通过传入'hue'的参数,来对x轴的字段进行细分,这里我们通过'who'来进行分类观察。
import seaborn as sns
import matplotlib.pyplot as plt
%matplotlib inline
titanic=sns.load_dataset('titanic')

# sns.boxplot(x='class',y='age',data=titanic)
sns.boxplot(x='class',y='age',hue='who',data=titanic)

在这里插入图片描述
与上述类似,我们也可以通过调换x/y轴,实现箱线图的横向显示。
sns.boxplot(x='age',y='class',hue='who',data=titanic)
在这里插入图片描述
调节'order' 和 'hue_order' 参数,我们可以控制x轴展示的顺序。

fig,axes=plt.subplots(1,2) 

sns.boxplot(x='class',y='age',hue='who',
                    data=titanic,ax=axes[0])

sns.boxplot(x='class',y='age',hue='who',data=titanic,
                    order=['Third','Second','First'],
                    hue_order=['child','woman','man'],ax=axes[1])

在这里插入图片描述
可以通过'linewidth'参数,控制线条的粗细。我们把'linewidth'参数设为1
sns.boxplot(x='class',y='age',hue='who', linewidth=1,data=titanic)


regplot/lmplot 回归图

Seaborn 中利用 regplot() 和 lmplot() 来进行回归,确定线性关系,它们密切相关,共享核心功能,但也有明显的不同。
图中的点表示实际的数据点,Seaborn 根据这些数据拟合出直线,表示x轴和y轴对应字段之间的线性关系,直线周围的阴影表示置信区间。

关于置信区间,可以通过设置’ci’参数控制是否显示。
sns.regplot(x='sepal_length',y='petal_length',data=iris,ci=None)
在这里插入图片描述
可以通过'color'和'marker'参数来控制图形的颜色以及数据点的形状。

fig,axes=plt.subplots(1,2) 

sns.regplot(x='sepal_length',y='petal_length',data=iris,
            color='r',marker='+',ax=axes[0])

sns.regplot(x='sepal_length',y='petal_length',data=iris,
            color='g',marker='*',ax=axes[1])

在这里插入图片描述

# lmplot() 可以设置hue,进行多个类别的显示,而 regplot() 是不支持的。这里我们通过设置hue='species',来进行分类别地展示。
#sns.lmplot(x='sepal_length',y='petal_length', hue='species',data=iris)
# 同样的,我们也可以更改数据点的形状,来进行区分。
sns.lmplot(x='sepal_length',y='petal_length',hue='species',
                    data=iris,markers=['*','o','+'])

在这里插入图片描述

# 设置'fit_reg'参数,可以控制是否显示拟合的直线。
sns.lmplot(x='sepal_length',y='petal_length',hue='species',
                data=iris,markers=['*','o','+'],fit_reg=False)

在这里插入图片描述


heatmap

Seaborn的heatmap各个参数介绍

  • seaborn.heatmap
    seaborn.heatmap(data, vmin=None, vmax=None, cmap=None, center=None, robust=False, annot=None, fmt=’.2g’, annotkws=None, linewidths=0, linecolor=‘white’, cbar=True, cbarkws=None, cbar_ax=None, square=False, ax=None, xticklabels=True, yticklabels=True, mask=None, **kwargs)

  • data:矩阵数据集,可以使numpy的数组(array),如果是pandas的dataframe,则df的index/column- 信息会分别对应到heatmap的columns和rows

  • linewidths,热力图矩阵之间的间隔大小

  • vmax,vmin, 图例中最大值和最小值的显示值,没有该参数时默认不显示

  • cmap:matplotlib颜色表名称或对象,或颜色列表,可选从数据值到色彩空间的映射。如果没有提供,默认设置

  • center:将数据设置为图例中的均值数据,即图例中心的数据值;通过设置center值,可以调整生成的图像颜色的整体深浅;设置center数据时,如果有数据溢出,则手动设置的vmax、vmin会自动改变

  • robust : 如果“Ture”和“ vmin或” vmax不存在,则使用强分位数计算颜色映射范围,而不是极值。

  • xticklabels, yticklabels : 可以以字符串进行命名,也可以调节编号的间隔,也可以不显示坐标

  • annot annotate的缩写,annot默认为False,如果为True,则将数据值写入每个单元格中

  • annot_kws,当annot为True时,可设置各个参数,包括大小,颜色,加粗,斜体字等

  • linewidths : 划分每个单元格的线的宽度。

  • linecolor : 划分每个单元格的线的颜色。

  • cbar : 是否绘制颜色条:colorbar,默认绘制

  • square : 为‘True’时,整个网格为一个正方形

  • fmt : 表格里显示数据的类型

fmt ='.0%'#显示百分比
fmt ='f' 显示完整数字 = fmt ='g'
fmt ='.3'显示小数的位数 = fmt ='.3f' = fmt ='.3g'
# 更改色彩图的限制:
import numpy as np; np.random.seed(0)
import seaborn as sns; sns.set()
uniform_data = np.random.rand(10, 12)
ax = sns.heatmap(uniform_data, vmin=0, vmax=1)

在这里插入图片描述

0为中心的数据绘制热图:
import numpy as np; np.random.seed(0)
import seaborn as sns; sns.set()
normal_data = np.random.randn(10, 12)
ax = sns.heatmap(normal_data, center=0)

在这里插入图片描述

import matplotlib.pyplot as plt
import seaborn as sns
sns.set()
#用行和列标签绘制
flights_long = sns.load_dataset("flights")
flights = flights_long.pivot("month", "year", "passengers")
# 绘制x-y-z的热力图,比如 年--销量 的热力图
f, ax = plt.subplots(figsize=(9, 6))
sns.heatmap(flights, ax=ax)
#设置坐标字体方向
label_y = ax.get_yticklabels()
plt.setp(label_y, rotation=360, horizontalalignment='right')
label_x = ax.get_xticklabels()
plt.setp(label_x, rotation=45, horizontalalignment='right')
plt.show()

在这里插入图片描述
使用整数格式用数值注释每个单元格:

import matplotlib.pyplot as plt
import seaborn as sns
sns.set()
flights_long = sns.load_dataset("flights")
flights = flights_long.pivot("month", "year", "passengers")
# 绘制x-y-z的热力图,比如 年--销量 的热力图
f, ax = plt.subplots(figsize=(9, 6))
#绘制热力图,还要将数值写到热力图上
sns.heatmap(flights, annot=True, fmt="d", ax=ax)
#设置坐标字体方向
label_y = ax.get_yticklabels()
plt.setp(label_y, rotation=360, horizontalalignment='right')
label_x = ax.get_xticklabels()
plt.setp(label_x, rotation=45, horizontalalignment='right')
plt.show()

在这里插入图片描述

在每个单元格之间添加行:
import numpy as np; np.random.seed(0)
import seaborn as sns; sns.set()
flights = sns.load_dataset("flights")
flights = flights.pivot("month", "year", "passengers")
ax = sns.heatmap(flights, linewidths=.5)

在这里插入图片描述
使用不同的颜色表:

import matplotlib.pyplot as plt
import seaborn as sns
sns.set()
flights_long = sns.load_dataset("flights")
flights = flights_long.pivot("month", "year", "passengers")
# 绘制x-y-z的热力图,比如 年--销量 的热力图
f, ax = plt.subplots(figsize=(9, 6))
#使用不同的颜色
sns.heatmap(flights, fmt="d",cmap='YlGnBu', ax=ax)
#设置坐标字体方向
label_y = ax.get_yticklabels()
plt.setp(label_y, rotation=360, horizontalalignment='right')
label_x = ax.get_xticklabels()
plt.setp(label_x, rotation=45, horizontalalignment='right')
plt.show()

在这里插入图片描述

以特定值居中色彩图:
import numpy as np; np.random.seed(0)
import seaborn as sns; sns.set()
flights = sns.load_dataset("flights")
flights = flights.pivot("month", "year", "passengers")
ax = sns.heatmap(flights, center=flights.loc["January", 1955])

在这里插入图片描述

不要绘制颜色条:
import numpy as np; np.random.seed(0)
import seaborn as sns; sns.set()
data = np.random.randn(10, 10)
ax = sns.heatmap(data, cbar=False)

在这里插入图片描述
对色条使用不同的轴:

import numpy as np; np.random.seed(0)
import seaborn as sns; sns.set()
import matplotlib.pyplot as plt

flights = sns.load_dataset("flights")
flights = flights.pivot("month", "year", "passengers")
grid_kws = {"height_ratios": (.9, .05), "hspace": .3}
f, (ax, cbar_ax) = plt.subplots(2, gridspec_kw=grid_kws)
ax = sns.heatmap(flights, ax=ax,cbar_ax=cbar_ax,cbar_kws={"orientation": "horizontal"})

在这里插入图片描述

使用掩码只绘制矩阵的一部分:

import numpy as np; np.random.seed(0)
import seaborn as sns; sns.set()

corr = np.corrcoef(np.random.randn(10, 200))
mask = np.zeros_like(corr)
mask[np.triu_indices_from(mask)] = True
with sns.axes_style("white"):
    ax = sns.heatmap(corr, mask=mask, vmax=.3, square=True)

在这里插入图片描述

import numpy as np; np.random.seed(0)
import seaborn as sns; sns.set()
import matplotlib.pyplot as plt
data = np.random.rand(10, 12)
f, ax = plt.subplots(figsize=(8,5))
ax = sns.heatmap(data,cmap = 'RdBu',ax=ax,vmin=0, vmax=1,annot=True,fmt ='0.1g')

#设置坐标字体方向
label_y = ax.get_yticklabels()
plt.setp(label_y, rotation=45, horizontalalignment='right')
label_x = ax.get_xticklabels()
plt.setp(label_x, rotation=45, horizontalalignment='right')
plt.xlabel('x.num')#设置坐标名称
plt.ylabel('y.num')
plt.title('Plotting')#标题
plt.show()

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值