想要改变世界,就得先改变自己。 ------ 博客首页

4-8 pie与布局

 

In [1]:
%matplotlib inline
import matplotlib.pyplot as plt
 

1.pie简单参数:plt.pie(x, explode=None, labels=None……)

属性说明类型
x 数据 list
labels 标签 list
autopct 数据标签 %0.1%% 保留一位小数
explode 突出的部分,分离程度 list
shadow 是否显示阴影 bool
pctdistance 数据标签的距离圆心位置 0~1
labeldistance 标签的比例 float
startangle 开始绘图的角度 float
radius 半径长 默认是1
In [2]:
m=51212.
f=40742
m_perc=m/(m+f)
f_perc=f/(m+f)

colors=['navy','lightcoral']
labels=["Male","Female"]

plt.figure(figsize=(5,5))#可控制圆的大小
paches,texts,autotexts=plt.pie([m_perc,f_perc],labels=labels,autopct='%1.1f%%',explode=[0,0.05],colors=colors)#画pie图

for text in texts+autotexts:
    text.set_fontsize(20)#设置字体大小
for text in autotexts:
    text.set_color('white')#设置字体颜色
 
 

2.设置子图布局

In [3]:
#3行3列的子图在0行0列的位置
ax1=plt.subplot2grid((3,3),(0,0))
ax2=plt.subplot2grid((3,3),(1,0))
ax3=plt.subplot2grid((3,3),(0,2),rowspan=3)#rowspan:在当前位置占用了几行
ax4=plt.subplot2grid((3,3),(2,0),colspan=2)#colspan:在当前位置占用了几列
ax5=plt.subplot2grid((3,3),(0,1),rowspan=2)
 
 

3.嵌套图

In [4]:
import numpy as np

x=np.linspace(0,10,1000)
y2=np.sin(x**2)
y1=x**2

fig,ax1=plt.subplots()#指定外层图
left,bottom,width,height=[0.22,0.45,0.3,0.35]#中间子图嵌套的位置
ax2=fig.add_axes([left,bottom,width,height])#加上子图

ax1.plot(x,y1)
ax2.plot(x,y2)
Out[4]:
[<matplotlib.lines.Line2D at 0x83e9da0>]
 
In [5]:
from mpl_toolkits.axes_grid1.inset_locator import inset_axes
#定义柱状图的标签位置定位函数
def autolabel(rects):
    for rect in rects:
        height=rect.get_height()
        ax1.text(rect.get_x()+rect.get_width()/2,1.02*height,
         "{:,}".format(float(height)),
         ha='center',va='bottom',fontsize=18)
        
        
#导入数据
top10_arrivals_countries=['CANADA','MWXICO','UNITED\nKINGDOM',\
                         'JAPAN','CHIAN','GERMANY','SOUTH\nKOREA',\
                         'FRANCE','BRAZIL','AUSTRALIA']
top10_arrivals_values=[16.6232,15.3245,3.1534,2.9954,\
                      2.6454,1.2545,1.6425,1.4253,\
                      1.3225,1.1354]
arrivals_countries=['WESTERN\nEUROPE','ASIA','SOUTH\nAMERICA',\
                   'OCEANIA','CARIBBEAN','MIDDLE\nEAST',\
                   'CENTEAL\nAMERICA','EASTERN\nEUROPE','AFRICA']
arrivals_percent=[36.9,30.4,13.8,4.4,4.0,3.6,2.9,2.6,1.5]

fig,ax1=plt.subplots(figsize=(20,12))#指定外层图
labell=ax1.bar(range(10),top10_arrivals_values,color='blue')#柱状图1
#写注释,柱状图
plt.xticks(range(10),top10_arrivals_countries,fontsize=10)

#画子图
ax2=inset_axes(ax1,width=6,height=6,loc=5)#添加子图小图,loc是具体位置

explode=(0.08,0.08,0.05,0.05,0.08,0.08,0.04,0.04,0.05)#缝隙距离
patchea,texts,autotexts=ax2.pie(arrivals_percent,labels=arrivals_countries,autopct='%1.1f%%',explode=explode)
#设置字体大小,子图
for text in texts+autotexts:
    text.set_fontsize(16)

#设置轴位置spines
for spine in ax1.spines.values():
    spine.set_visible(False)#指定下面轴不可见
#柱状图label标注数据
autolabel(labell)
 
posted @ 2019-10-28 10:30  karina512  阅读(313)  评论(0编辑  收藏  举报