对于常用的python可视化对应的matplotlib的图形样式,进行补充和说明!
一. 设置坐标轴的刻度样式
1.1 刻度定位器和刻度格式器的使用方法
函数 tick_params()
参数解析:
which #设置刻度样式
length #设置刻度长度
width #设置刻度宽度
colors #设置刻度线和刻度标签颜色
labelsize #设置次要刻度标签的大小
labelcolor #设置次要刻度标签的颜色
1.2 调用模块pyplot中的函数实现刻度样式的设置
#1.2 调用模块pyplot中的函数实现刻度样式的设置
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)
ax.xaxis.set_major_locator(MultipleLocator(1.0))
ax.yaxis.set_major_locator(MultipleLocator(1.0))
ax.xaxis.set_minor_locator(AutoMinorLocator(4))
ax.xaxis.set_minor_locator(AutoMinorLocator(4))
def minor_tick(x,pos):
if not x % 1.0:
return ""
return "%0.2f" % x
ax.xaxis.set_minor_formatter(FuncFormatter(minor_tick))
ax.tick_params("y",which = "major",
length = 15,
width = 1.0,
labelsize = 10,
labelcolor = '0.25'
)
ax.set_xlim(0,4)
ax.set_ylim(0,2)
ax.plot(x,y,
c = (0.25,0.25,1.00),
lw = 2,
zorder = 10
)
ax.grid(linestyle = "-",
linewidth = 0.5,
color = 'r',
zorder = 0
)
plt.show()
1.3 案例1-刻度标签和刻度线样式的定制化
#1.3 案例1-刻度标签和刻度线样式的定制化
import matplotlib as mpl
import matplotlib.pyplot as plt
import numpy as np
fig = plt.figure(facecolor = (1.0,1.0,0.9412))
ax = fig.add_axes([0.1,0.4,0.5,0.5])
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)
plt.show()
1.4 案例2-货币和时间序列样式的刻度标签
#1.4 案例2-货币和时间序列样式的刻度标签
import matplotlib.pyplot as plt
import numpy as np
plt.rcParams["font.sans-serif"] = ["lisu"]
plt.rcParams["axes.unicode_minus"] = False
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])
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()
二. 添加有指示注解和无指示注解
2.1 有注释和无注释的添加方法
函数 annotate(s,xy,xycoords,xytext,textcoords,weight,color,arrowprops)#添加有提示注解
参数解析:
s #注释的内容
xy #解释内容的位置
xycoords #xy的坐标系统
xytext #注释内容所在的位置,矩阵的左下顶点位置
textcoords #xytext的坐标系统
weight #注释内容的显示风格
color #注释内容的颜色
arrowprops #指示箭头的属性,包括箭头风格,颜色
函数 text(x,y,s,**kw)#添加无提示注解
参数解析:
x,y #注释的横纵坐标,矩阵的左下顶点位置
s #注释的内容
import matplotlib.pyplot as plt
import numpy as np
plt.rcParams["font.sans-serif"] = ["lisu"]
plt.rcParams["axes.unicode_minus"] = False
x = np.linspace(0.5,3.5,100)
y = np.sin(x)
fig = plt.figure(figsize = (8,8))
ax = fig.add_subplot(111)
ax.plot(x,y,c = "b",ls = "--",lw = 2)
#有指示注释
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"#指示箭头的颜色
)#指示箭头的属性
)
#无指示注释
ax.text(2.8,0.4,#注解形成的左下角顶点的横纵坐标
"$y=\sin(x)$",
fontsize = 20,#注解的大小是20
color = "b",#注解字体为蓝色
bbox = dict(facecolor = "y",alpha = 0.5)
)
plt.show()
2.2 案例1-圆角文本框的设置
#2.2 案例1-圆角文本框的设置
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(0.0,10,40)
y = np.random.randn(40)
plt.plot(x,y,
ls = "-",
lw = 2,
marker = "o",
ms = 20,
mfc = "orange",
alpha = 0.6
)
plt.grid(ls = ":",color = "gray",alpha = 0.5)
plt.text(6,0,
"Matplotlib",
size = 30,
rotation = 30.,
bbox = dict(boxstyle = "round",
ec = "#8968CD",
fc = "#FFE1FF"
)
)
plt.savefig("圆角文本框.jpg",dpi = 300)#保存圆角文本框
plt.show()
2.3 案例2-文本的水印效果
#2.3 案例2-文本的水印效果
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(0.0,10,40)#生成均匀分布的数值序列
y = np.random.randn(40)
plt.plot(x,y,
ls = "-",
lw = 2,
marker = "o",
ms = 20,#中间点的大小
mfc = "orange",#中间点颜色
mec = "red",#点边缘颜色
alpha = 0.6
)
plt.grid(ls = ":",color = "gray",alpha = 0.5)
plt.text(1,2,
"Matplotlib",
fontsize = 50,
color = "gray",
alpha = 0.5
)
plt.show()
2.4 案例3-圆角线框的有弧度注释
#2.4 案例3-圆角线框的有弧度注释
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(0,10,2000)
y = np.sin(x) * np.cos(x)
fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot(x,y,ls = "-",lw = 2)
bbox = dict(boxstyle = "round",
fc = "#7ec0ee",
ec = "#9b30ff"
)
arrowprops = dict(arrowstyle = "-|>",
connectionstyle = "angle,angleA = 0,angleB = 90,rad = 10",
color = "r"
)
ax.annotate("single point",
(5,np.sin(5)*np.cos(5)),
xytext = (3,np.sin(3)*np.cos(3)),
fontsize = 12,
color = "r",
bbox = bbox,
arrowprops = arrowprops
)
ax.grid(ls = ":",color = "gray",alpha = 0.6)
plt.show()
2.5 案例4-有箭头指示的趋势线
#2.5 案例4-有箭头指示的趋势线
'''
函数 arrow(x,y,dx,dy)
参数解析:
dx #参数x的水平增量
dy #参数y的垂直增量
'''
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(0,10,2000)
y = np.sin(x)
fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot(x,y,ls = "-",lw = 2)
ax.set_ylim(-1.5,1.5)
arrowprops = dict(arrowstyle = "-|>",color = "r")
ax.annotate("",
xy = (3/2*np.pi,np.sin(3/2*np.pi) + 0.05),#被解释的位置
xytext = (np.pi/2,np.sin(np.pi/2)+0.05),#注释内容所在位置的左下角坐标
color = "r",#注释内容的颜色
weight = "bold",#注释内容的显示风格
arrowprops = arrowprops#指示箭头的属性
)
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()
2.6 案例5-桑葚图
2.6 案例5-桑葚图
import matplotlib as mpl
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.sankey import Sankey
plt.rcParams["font.sans-serif"] = ["fangsong"]
plt.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]#显示 -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()
#练习桑葚图
import matplotlib as mpl
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.sankey import Sankey
plt.rcParams["font.sans-serif"] = ["fangsong"]
plt.rcParams["axes.unicode_minus"] = False
flows = [9000,-425,-1700,-2300,-610,-1420,-300,-1800]
labels = ["工资收入","京东白条","融易分期","微信还款","花呗","房租水费","电费交通","日常伙食"]
orientations = [1,-1,1,0,1,-1,1,-1]
sankey = Sankey()
sankey.add(flows = flows,
labels = labels,
orientations = orientations,
color = "c",
fc = "lightgreen",
patchlabel = "月常开销",
alpha = 0.7
)
diagrams = sankey.finish()
diagrams[0].texts[6].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()
三.实现标题和坐标轴标签的投影效果
3.1 实现标题和坐标轴标签的投影效果操作方法
3.1 实现标题和坐标轴标签的投影效果操作方法
import matplotlib.pyplot as plt
import matplotlib.patheffects as pes
import numpy as np
x = np.linspace(0.5,3.5,100)
y = np.sin(x)
fontsize = 23
plt.plot(x,y,ls = "--",lw = 2)
title = "$y=\sin({x})$"
xaxis_label = "$x\axis$"
yaxis_label = "$y\axis$"
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)
title_text_obj.set_path_effects([pes.withSimplePatchShadow()])
pe = pes.withSimplePatchShadow(offset = (1,-1),shadow_rgbFace = "r",alpha = 0.3)
xaxis_label_text_obj.set_path_effects([pe])
yaxis_label_text_obj.set_path_effects([pe])
plt.show()
3.2 案例-给坐标轴标签添加文本框
3.2 案例-给坐标轴标签添加文本框
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(0.5,3.5,100)
y = np.sin(x)
fig = plt.figure(figsize = (8,8))
ax = fig.add_subplot(111)
box = dict(facecolor = "#6959cd",pad = 2,alpha = 0.4)
ax.plot(x,y,c = "b",ls = "--",lw = 2)
title = "$y = \sin({x})$"
plt.title(title, color='green', fontsize=22)
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)
ax.xaxis.set_label_coords(1.0,-0.05)
ax.grid(ls="-",lw = 1,color = "white",alpha = 0.5)
plt.gca().set_facecolor('yellow')
plt.savefig("坐标轴标签添加文本框.png",dpi = 500)
plt.show()