Python数据可视化之matplotlib实践--精进部分

763 阅读5分钟

本文为学习笔记,仅供自己复习回顾使用,若有侵权可删除

第五章图形样式

刻度样式

定位器( locator):刻度定位器用来设置刻度线的位置;
刻度格式器( formatter):刻度格式器用来设置刻度标签的显示样式.

import matplotlib.pyplot as plt
import numpy as np
from matplotlib.ticker import AutoMinorLocator, MultipleLocator, FuncFormatter
x = np.linspace(0.5,3.5,100)
y = np.sin(x)
fig = plt.figure(figsize=(8,8))
ax = fig.add_subplot(111)  #生成一个 Axes 实例 ax

# set x y-major_tick_locator
ax.xaxis.set_major_locator(MultipleLocator(1.0)) #在 x 轴的 1 倍处分别设置主刻度线
ax.yaxis.set_major_locator(MultipleLocator(1.0))

# set x,y-minor_tick_locator
ax.xaxis.set_minor_locator(AutoMinorLocator(4)) #设置次要刻度线的显示位置,将每个煮刻度四等分
ax.yaxis.set_minor_locator(AutoMinorLocator(4))

# set x-minor_tick_formatter
def minor_tick(x, pos): # n % n = 0; m % n = m(m<n)
    if not x % 1.0:
        return ""
    return "%.2f" % x

ax.xaxis.set_minor_formatter(FuncFormatter(minor_tick)) #设置次要刻度线显示位置的精度

# change the appearance of ticks and tick labels 刻度样式的设置
ax.tick_params("y",which='major',length=15,width=2.0,colors="r") #主
ax.tick_params(which='minor',length=5,width=1.0,labelsize=10, labelcolor='0.25') #次
'''
语句“ax.tick_params()”是通过调用实例 ax 的实例方法进行刻度样式设置的。
同时,通过调用模块 pyplot 中的函数也可以实现刻度样式的设置工作。具体而言,模块 pyplot 中的
刻度样式的设置是通过函数 tick_params()实现的,即可以执行语句“plt.tick_params()” 来进行刻度样
式的设置。
'''
fig = plt.figure(facecolor=(1,1,0.9412)) #figure实例,设置了画布的背景颜色
ax = fig.add_axes([0.1,0.4,0.5,0.5]) #实例ax ,坐标轴位置和大小的四元列表
for ticklabel in ax.xaxis.get_ticklabels():
    ticklabel.set_color("slateblue")
    ticklabel.set_fontsize(18)
    ticklabel.set_rotation(30)
for tickline in ax.yaxis.get_ticklines():
    tickline.set_color("lightgreen")
    tickline.set_markersize(20) #刻度线长度
    tickline.set_markeredgewidth(2) #刻度线宽度

时序

ax.yaxis.set_major_formatter(FormatStrFormatter(r"$\yen%1.1f$")) #作为参数值代入实例,货币标签

注释

有对细节做出标志的有指示注解和对整体做出说明的无指示注解两类。
有指示注解和无指示注解的主要区别是有无箭头显示,也就是对被解释内容的精确定位。

#有指使注释
ax.annotate("maximum",                    #注解的内容
            xy=(np.pi/2,1.0),            #被解释内容的位置
            xycoords="data",           #xy 的坐标系统,参数值 data 表示与折线图使用相同的坐标系统
            xytext=((np.pi/2)+0.15,0.8),  #注释内容所在的位置
            textcoords="data",    #xytext 的坐标系统
            weight="bold",    #注解内容的显示风格
            color="r",    #注解内容的颜色
            arrowprops=dict(arrowstyle="->",connectionstyle="arc3",color="r")  #指示箭头的属性,包括箭头风格、 颜色等
           )
#arrowprops = dict(arrowstyle="-|>",connectionstyle="angle,angleA=0,angleB=90,rad=10",color="r") #有弧度的箭头

ax.arrow(0.0,-0.4,np.pi/2,1.2,head_width=0.1, head_length=0.2,fc='g', ec='g') #绿箭头,箭头不是正三角
#arrow(x,y,dx,dy)中的参数 dx 是参数 x 的水平增量,对应的参数 dy 是参数 y 的垂直增量


# Annotate the whole points with text without the "arrowstyle"
# 无指示注释
ax.text(2.8,0.4,"$y=\sin(x)$",fontsize=20,color="b",bbox=dict(facecolor='y', alpha=0.5))
# 圆角框boxstyle="round"”实现的,其中的键值“round”还可以改成“square”,进而形成直角线框
# bbox=dict(boxstyle="round",ec="#8968CD",fc="#FFE1FF")

桑基图

flows=[0.2,0.1,0.4,0.3,-0.6,-0.05,-0.15,-0.2] #列表 flows 中的负值表示流出量,正值表示流入量
labels=["","","","","family","trip","education","sport"]
orientations=[1,1,0,-1,1,-1,1,0] #−101 分别表示流量的显示位置在下方、水平和上方

sankey = Sankey()
sankey.add(flows=flows,labels=labels,orientations=orientations,color="c",
           fc="lightgreen",patchlabel="Life Cost",alpha=0.7)
diagrams = sankey.finish()

#调整流量图 diagrams[0]的文本“ListCost”和“family”的显示样式、颜色等属性的属性值
diagrams[0].texts[4].set_color("r")
diagrams[0].texts[4].set_weight("bold")
diagrams[0].text.set_fontsize(20)
diagrams[0].text.set_fontweight("bold")

设置文本阴影、文本框效果

#阴影
# set text contents
title = "$y=\sin({x})$"
xaxis_label = "$x\_axis$"
yaxis_label = "$y\_axis$"

# get text instance
title_text_obj = plt.title(title,fontsize=fontsize,va="bottom")
xaxis_label_text_obj =plt.xlabel(xaxis_label,fontsize=fontsize-3,alpha=1.0)
yaxis_label_text_obj =plt.ylabel(yaxis_label,fontsize=fontsize-3,alpha=1.0)

# set shadow
title_text_obj.set_path_effects([pes.withSimplePatchShadow()])
pe = pes.withSimplePatchShadow(offset=(1,-1), #文本内容投影相对文本内容本身的偏离距离
                               shadow_rgbFace="r",  #投影的颜色
                               alpha=.3)
xaxis_label_text_obj.set_path_effects([pe])
yaxis_label_text_obj.set_path_effects([pe])

#文本框
ax = fig.add_subplot(111)
box = dict(facecolor="#6959CD",pad=2,alpha=0.4)
ax.plot(x, y, c="b", ls="--",lw=2)

# set text contents
title = "$y=\sin({x})$"
xaxis_label = "$x\_axis$"
yaxis_label = "$y\_axis$"

ax.set_xlabel(xaxis_label,fontsize=18,bbox=box)
ax.set_ylabel(yaxis_label,fontsize=18,bbox=box)

ax.set_title(title,fontsize=23,va="bottom")

ax.yaxis.set_label_coords(-0.08,0.5) # axes coords
ax.xaxis.set_label_coords(1.0,-0.05) # axes coords 
'''
实例方法 set_label_coords()是确定文本位置的关键,实例方法 set_label_coords()的参数采用 Axes 坐标轴系统,
即取值范围从 0.0 到 1.0,数值取负数表示与坐标轴方向相反的距离
'''

第六章划分画布

subplot

plt.subplot(121)

ax = plt.subplot(111,polar=True) #极坐标
ax.plot(theta,radii,color="r",linestyle="-",linewidth=2)  #极径和极角作为折线图的数量参数

非等分画布

ax1 = fig.add_subplot(121)
ax1.margins(0.033)  #数据范围的空白区域,大于−0.5 的任意浮点数
ax1.plot(x,y,ls="-",lw=2,color="b")

ax2 = fig.add_subplot(222)
ax2.margins(0.7,0.7)
ax2.plot(x,y,ls="-",lw=2,color="r")

ax3 = fig.add_subplot(224)
ax3.margins(x=0.1,y=0.3)
ax3.plot(x,y,ls="-",lw=2,color="g")

subplot2grid非等分画布

plt.subplot2grid((2,3),(0,0),colspan=2) #23列,将第一行和第一列作为位置起点,跨越两列
x = np.linspace(0.0,4.0,100)
y = np.random.randn(100)
plt.scatter(x,y,c="c")
plt.title("散点图")
# set subplot(233)

plt.subplot2grid((2,3),(0,2))
plt.title("空白绘图区域")

# set subplot(23,4-6)
plt.subplot2grid((2,3),(1,0),colspan=3)
x = np.linspace(0.0,4.0,100)
y1 = np.sin(x)
plt.plot(x,y1,lw=2,ls="-")

利用gridspec进行非等分画布

模块 gridspec 是一个可以指定画布中子区位置或者说是布局的“分区”模块
类 GridSpec 可以指定网格的几何形状

fig = plt.figure()
gs = GridSpec(2, 2) #22列
box = {"facecolor":"lightgreen","pad":3,"alpha":0.2}
# subplot(2,2,1-2)
x1 = np.arange(0, 1e5, 500)

ax1 = fig.add_subplot(gs[0, :],fc="yellowgreen")  #第一行
ax1.plot(x1,"k--",lw=2)
ax1.set_ylabel('YLabel0,0-1',bbox=box)
ax1.set_xlabel('XLabel0,0-1',bbox=box)
ax1.yaxis.set_label_coords(-0.1,0.5)
# subplot(2,2,3)
x2 = np.linspace(0,1000,10)
y2 = np.arange(1,11,1)

ax2 = fig.add_subplot(gs[1,0],fc="cornflowerblue")  #第二行第一列
ax2.scatter(x2,y2,s=20,c="grey",marker="s",linewidths=2,edgecolors="k")
ax2.set_ylabel("YLabel10",bbox=box)
ax2.set_xlabel("XLabel10",bbox=box)
for ticklabel in ax2.get_xticklabels():
    ticklabel.set_rotation(45)
ax2.yaxis.set_label_coords(-0.25,0.5)  #  y 轴坐标轴标签的位置对齐
ax2.xaxis.set_label_coords(0.5,-0.25)
# subplot(2,2,4)
x3 = np.linspace(0,10,100)
y3 = np.exp(-x3)

ax3 = fig.add_subplot(gs[1,1])  #第二行第二列
ax3.errorbar(x3,y3,fmt="b-",yerr=0.6*y3,ecolor="lightsteelblue",elinewidth=2,capsize=0,errorevery=5)
ax3.set_ylabel("YLabel11",bbox=box)
ax3.set_xlabel("XLabel11",bbox=box)
ax3.xaxis.set_label_coords(0.5,-0.25)
ax3.set_ylim(-0.1,1.1)
ax3.set_yticks(np.arange(0,1.1,0.1))
gs.tight_layout(fig)

subplot综合

#1个子图同时设置了背景颜色
fig, ax = plt.subplots(1,1,subplot_kw=dict(fc="cornflowerblue"))

#y轴共享
fig, ax = plt.subplots(1,2,sharey=True)

第七章共享坐标轴

统一坐标系下共享

fig, ax1 = plt.subplots()
t = np.arange(0.05,10.0,0.01)
s1 = np.exp(t)
ax1.plot(t,s1,c="b",ls="-")

# set x-axis label
ax1.set_xlabel("x 坐标轴")
# Make the y-axis label, ticks and tick labels match the line color.
ax1.set_ylabel("以 e 为底指数函数", color="b")
ax1.tick_params("y", colors="b")

# ax1 shares x-axis with ax2.
ax2 = ax1.twinx()  #生成实例 ax2,此时实例 ax2 的 x 轴与实例 ax1 的 x 轴是共享的
#相应的,我们也可以调用 Axes.twiny()实例方法满足共享 y 轴的可视化需求
s2 = np.cos(t**2)
ax2.plot(t,s2,c="r",ls=":")
# Make the y-axis label, ticks and tick labels match the line color.
ax2.set_ylabel("余弦函数",color="r")
ax2.tick_params("y", colors="r")
plt.show()

子图中共享坐标轴

调整函数 subplots()中的参数 sharey(或是参数 sharex)的不同取值情况,从而实现共享不同子区的绘图区域的坐标轴的需求。

#sharex="all" 取值范围中上限里的最大值
#sharex="none" 取值范围中上限里的最大值
#sharex="row" 每一行的图形的 x 轴取值范围实现共享
#sharex="col" 每一列的图形的 x 轴取值范围实现共享
fig,ax = plt.subplots(2, 2, sharex="all") 

###### 共享个别子区绘图区域的坐标轴
fig,ax = plt.subplots(2, 2)
# set chart of each subplot
ax1 = plt.subplot(221)
ax1.plot(x1,y1)
ax2 = plt.subplot(222)
ax2.plot(x2,y2)
ax3 = plt.subplot(223)
ax3.scatter(x3,y3)
ax4 = plt.subplot(224,sharex=ax1)  #第四个子图共享第一个子图的x轴
ax4.scatter(x4,y4)

子图共享坐标轴时去掉子图之间间隙

fig,(ax1,ax2,ax3,ax4) = plt.subplots(4,1,sharex="all") fig.subplots_adjust(hspace=0) #将 4 幅子图的水平方向的空隙去除

用函数 autoscale()调整坐标轴范围

ax3.scatter(x3,y3)
plt.autoscale(enable=True,axis="both",tight=True)  #用函数 autoscale()调整坐标轴范围
'''
   enable:进行坐标轴范围的自适应调整。
 axis:使 x、 y 轴都进行自适应调整。
 tight:让坐标轴的范围调整到数据的范围上。
'''