【学习笔记】python数据可视化之matplotlib实践第五章

统计图形绘制进阶:图形样式

(1)设置坐标轴的刻度样式

1.刻度标签和刻度线样式的定制化

import matplotlib.pyplot as plt
import numpy as np

fig = plt.figure(facecolor = (1.0,1.0,0.9412))#创建了一个新的图形窗口,并设置背景颜色为(1.0,1.0,0.9412)
ax = fig.add_axes([0.1,0.4,0.5,0.5])#在图形窗口添加一个新的轴,并指定相对于图形窗口的总宽度和高度的归一化坐标;[0.1,0.4,0.5,0.5]表示轴的左下角位置在(0.1,0.4),宽度为0.5,高度为0.5
#将坐标轴刻度线放置内部,axis有三个参数(y,x,both)
ax.tick_params(axis = 'both',direction = 'in')
#设置x轴的标签
for ticklabel in ax.xaxis.get_ticklabels():
    ticklabel.set_color('slateblue')
    ticklabel.set_fontsize(18)
    ticklabel.set_rotation(30)
#设置y轴上的坐标轴刻度线
for tickline in ax.yaxis.get_ticklines():
    tickline.set_color('lightgreen')
    tickline.set_markersize(20)
    tickline.set_markeredgewidth(2)

plt.show()

以上已经对一些代码用途进行了注释说明,这里在重点强调一下代码中出现的一些陌生的函数:

1.首先生成figure实例fig,然后通过向画布添加坐标轴生成实例ax

2.ax.tick_params()通过调用实例ax的实例方法进行刻度样式设置,也可以调用plt.tick_params()函数实现,前者是matplotlib面向对象的操作方法,后者是调用模块pyplot的API的操作方法。

3.通过ax.xaxis获得x轴实例,调用实例方法get_ticklabels()获得Text实例列表,使用for循环对实例元素Text进行不同属性的属性值的设置。

4.同理,通过ax.yaxis获得y轴实例,从而借助实例方法get_ticklines()获得Line2D实例列表,也是for循环对实例元素Line2D进行不同属性的属性值的设置。

以下呈现上述代码运行结果:

2.货币和时间序列样式的刻度标签

import matplotlib.pyplot as plt
import numpy as np

from calendar import month_name,day_name
from matplotlib.ticker import FormatStrFormatter

fig = plt.figure()
ax = fig.add_axes([0.2,0.2,0.7,0.7])
#将坐标轴刻度线放置内部,axis有三个参数(y,x,both)
ax.tick_params(axis = 'both',direction = 'in')

x = np.arange(1,8,1)
y = 2*x
ax.plot(x,y,ls = '-',lw = 2,color = 'orange',marker = 'o',ms = 20,mfc = 'c',mec = 'c')

ax.yaxis.set_major_formatter(FormatStrFormatter(r'$\yen%1.1f$'))
plt.xticks(x,day_name[0:7],rotation = 20)

ax.set_xlim(0,8)
ax.set_ylim(0,18)

plt.show()

1.对于日期标签,我们通过导入calendar中的day_name实例获取日期形式的刻度标签

2.对于货币标签,通过从模块ticker中导入类FormatStrFormatter,将实例FormatStrFormatter(r'$\yen%1.1f$')作为参数值代入设置 y 轴主刻度的格式化器ax.yaxis.set_major_formatter(),其中r'$\yen%1.1f$'用于生成保留两位有效数字的人民币计量的刻度标签。

(2)添加有指示注解和无指示注解

1.有指示注解和无指示注解的添加方法

我们在这里先重新介绍以下有指示注解需要使用到的函数annotate(s,xy,xycoords,xytext,textcoords,weight,color,arrowprops)的相关参数:

s注解的内容
xy需要进行解释的位置即被解释内容的位置
xycoordsxy的坐标系统,参数值'data'表示与折线图使用相同的坐标系统
xytext注释内容的所在位置
textcoordsxytext的坐标风格
weight注解内容的显示风格
color注解内容的颜色
arrowprops指示箭头的属性,包含箭头的风格、颜色

 

 

 

 

 

 

 

 无指示注解使用到的函数text()的参数与前面文章中提到基本一致,在此就不进行赘述。

import matplotlib.pyplot as plt
import numpy as np


fig = plt.figure(figsize=(8,8))
ax = fig.add_subplot(111)

ax.tick_params(axis = 'both',direction = 'in')

x = np.linspace(0.5,3.5,100)
y = np.sin(x)
ax.plot(x,y,ls = '--',lw = 2,color = 'b')

ax.annotate('maximum',xy = (np.pi/2,1.0),xycoords = 'data',xytext = ((np.pi/2)+0.15,0.8),textcoords= 'data',weight = 'bold',color = 'r',arrowprops=dict(arrowstyle = '->',connectionstyle = 'arc3',color = 'r'))
ax.text(2.8,0.4,'$y = sin(x)$',fontsize = 20,color = 'b',bbox = dict(facecolor = 'y',alpha = 0.5))#bbox = dict(facecolor = 'y',alpha = 0.5)设置了一个文本框

plt.show()

运行结果: 

 2.圆角文本框的设置(在无指示注解基础上)

此部分将在上面代码的基础上进行修改讲解:

在上面代码中只需将text函数部分修改成下列代码这样的样式即可实现圆角文本框的设置:

ax.text(2.8,0.4,'$y = sin(x)$',size = 20,rotation = 30,bbox = dict(boxstyle = 'round',ec = '#8968CD',fc = '#FFE1FF'))#ec设置边框颜色,fc设置边框内部填充颜色

运行结果为: 

要想将边框设置为直角,只需要将改动一个参数即可,如下代码:

ax.text(2.8,0.4,'$y = sin(x)$',size = 20,rotation = 30,bbox = dict(boxstyle = 'square',ec = '#8968CD',fc = '#FFE1FF'))#ec设置边框颜色,fc设置边框内部填充颜色

运行结果: 

3.文本的水印效果(在无指示注解的基础上)

同样的我们只需要将text函数改写为以下代码就可以实现文本的水印效果:

ax.text(2.8,0.4,'$y = sin(x)$',fontsize = 20,color = 'c',alpha = 0.5)

运行结果: 

 4.圆角线框的有弧度指示的注解

这里我们只需要修改2.1中的代码的annotate()部分即可,将该部分换成以下代码即可实现圆角线框的有弧度指示的注解

ax.annotate('maximum',xy = (np.pi/2,1.0),xytext = ((np.pi/2)+0.15,0.8),fontsize = 12,color = 'r',bbox = dict(boxstyle = 'round',fc = '#7EC0EE',ec = '#9B30FF'),arrowprops=dict(arrowstyle = '-|>',connectionstyle = 'angle,angleA = 0,angleB = 90,rad = 10',color = 'r'))

在代码中我们需要注意到在设置箭头属性中的connectionstyle参数,该参数是设置连接的样式的,

“angle” 表示连接样式为角度连接。

“angleA = 0” 表示起始点的角度为 0 度。

“angleB = 90” 表示结束点的角度为 90 度。

“rad = 10” 表示曲率半径为 10

运行结果: 

 

5.有箭头指示的趋势线

我们可以使用没有文本指示箭头作为趋势线来反映折线的趋势变化和周期规律。以下代码我们使用两种方式实现有箭头指示的趋势线:1.annotate 2.arrow

import matplotlib.pyplot as plt
import numpy as np


fig = plt.figure()
ax = fig.add_subplot(111)

ax.tick_params(axis = 'both',direction = 'in')

x = np.linspace(0,10,2000)
y = np.sin(x)
ax.plot(x,y,ls = '-',lw = 2,color = 'b')

ax.annotate('',xy = (3*np.pi/2,np.sin(3*np.pi/2)+0.05),xytext = ((np.pi/2),np.sin(np.pi/2)+0.05),color = 'r',arrowprops=dict(arrowstyle = '-|>',color = 'r'))
ax.arrow(0.0,-0.4,np.pi/2,1.2,head_width = 0.05,head_length = 0.1,fc = 'g',ec = 'g')

ax.grid(ls = ':',color = 'gray',alpha = 0.6)
plt.show()

ax.arrow(0.0,-0.4,np.pi/2,1.2,head_width = 0.05,head_length = 0.1,fc = 'g',ec = 'g')中参数说明:(0.0,-0.4)表示箭头的起始坐标;

(np.pi/2,1.2)表示箭头的位移量,即从起始点沿x方向移动pi/2,沿y方向移动1.2;

  head_width设置箭头头部的宽度;

  head_length设置箭头头部的长度;

  fc设置箭头的填充颜色;

  ec设置箭头的边框颜色

运行结果:

特别说明:借助Axes的实例方法arrow()绘制出的图的箭头不是正三角形,借助Axes的实例方法annotate()绘制出没有注解的指示箭头,而且箭头为正三角形

6.桑基图

 有指示注解可以抽象为一种图形,即桑基图。桑基图是一种特定类型的流量图,在流量图中,指示箭头的宽度与流量的大小成比例。流量图可以可视化呈现能量、物质或是成本在流动过程中的转移情况。

import matplotlib.pyplot as plt
import numpy as np
import matplotlib as mpl

from matplotlib.sankey import Sankey

mpl.rcParams['font.sans-serif'] = ['FangSong']
mpl.rcParams['axes.unicode_minus'] = False

flows = [0.2,0.1,0.4,0.3,-0.6,-0.05,-0.15,-0.2]
labels = ['','','','','family','trip','education','sport']
orientations = [1,1,0,-1,1,-1,1,0]

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].texts[4].set_color('r')
diagrams[0].texts[4].set_weight('bold')
diagrams[0].text.set_fontsize(20)
diagrams[0].text.set_fontweight('bold')

plt.title('日常生活的成本开支的流量图')
plt.show()

代码说明:1. 从matplotlib中的模块sankey导入类Sankey,调用语句Sankey()生成实例sankey

2.列表flows中的负值表示流出量,正值表示流入量

3.列表orientations的-1,1,0表示流量的显示的位置在下方,上方,水平。

4.调用 sankey.finish() 方法生成桑基图对象,并将其赋值给 diagrams。这个对象可能包含了桑基图的各个组成部分,如线条、节点、文本等

运行结果:

 (3)实现标题和坐标轴标签的投影效果

1.给坐标轴标签添加文本框

import matplotlib.pyplot as plt
import numpy as np


fig = plt.figure(figsize=(8,8))
ax = fig.add_subplot(111)

ax.tick_params(axis = 'both',direction = 'in')

x = np.linspace(0.5,3.5,100)
y = np.sin(x)
ax.plot(x,y,ls = '--',lw = 2,color = 'b')

title = '$y = sin({x})$'
xaxis_label = '$x\\_axis$'
yaxis_label = '$y\\_axis$'

box = dict(facecolor = '#6959CD',pad = 2,alpha = 0.4)#pad=2 设置文本框的内边距为 2
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')#va='bottom' 将标题垂直对齐方式设置为底部对齐

ax.yaxis.set_label_coords(-0.08,0.5)
ax.xaxis.set_label_coords(1.0,-0.05)

ax.grid(ls = '-',lw = 1,color = 'gray',alpha = 0.5)
plt.show()

代码说明:实例方法set_label_coords()参数采用Axes坐标轴系统,即这里的坐标是相对的坐标,并不是按照之前绝对坐标一样

运行结果:

2.实现标题和坐标轴标签的投影效果的操作方法

 withSimplePatchShadow()主要参数介绍:

offset文本内容投影相对文本内容本身的偏离距离
shadow_rgbFace投影的颜色
alpha投影的透明度,范围为0-1,数值越大透明度越小

 

 

 

 

import matplotlib.pyplot as plt
import numpy as np
import matplotlib.patheffects as pes

fig = plt.figure(figsize=(8,8))
ax = fig.add_subplot(111)

ax.tick_params(axis = 'both',direction = 'in')

x = np.linspace(0.5,3.5,100)
y = np.sin(x)
ax.plot(x,y,ls = '--',lw = 2,color = 'b')

title = '$y = sin({x})$'
xaxis_label = '$x\\_axis$'
yaxis_label = '$y\\_axis$'

xlabel = ax.set_xlabel(xaxis_label,fontsize = 18,alpha = 1)
ylabel = ax.set_ylabel(yaxis_label,fontsize = 18,alpha = 1)
title = ax.set_title(title,fontsize = 23,va = 'bottom')
#设置阴影
title.set_path_effects([pes.withSimplePatchShadow()])
pe = pes.withSimplePatchShadow(offset=(1,-1),shadow_rgbFace='r',alpha = .3)
xlabel.set_path_effects([pe])
ylabel.set_path_effects([pe])

plt.show()

 代码说明:主要是调用Artist.set_path_effects(path_effects)来实现,实例方法set_path_effects(path_effects)中的参数path_effects是实例列表,列表中的实例就是调用pes类中的withSimplePatchShadow类

运行结果:

 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值