Python数据可视化之matplotlib实践--演练部分

126 阅读3分钟

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

第八章坐标轴高阶

向画布中任意位置添加任意数量的坐标轴

plt.axes([0.05,0.7,.3,.3], frameon=True,fc="y",aspect="equal")
'''
rect=[left,bottom,width,height]
    列表 rect 中的 left 和 bottom 两个元素分别表示坐标轴的左侧边缘和底部边缘距离画布边缘的距离,
    width 和 height 两个元素分别表示坐标轴的宽度和高度, 
    left 和 width 两个元素的数值都是画布宽度的归一化距离,
    bottom 和 height 两个元素的数值都是画布高度的归一化距离。
frameon 的含义是如果布尔型参数 frameon 取值 True,则绘制坐标轴的四条轴脊;否则,不绘制坐标轴的四条轴脊。
fc 的含义是填充坐标轴背景的颜色。
'''
plt.plot(np.arange(3), [0,1,0], color="blue", linewidth=2, linestyle="--")
# set #2 plot
plt.axes([0.3,0.4,.3,.3], frameon=True,fc="y",aspect="equal")
plt.plot(2+np.arange(3), [0,1,0], color="blue", linewidth=2, linestyle="-")
plt.axis([2.1,3.9,0.5,1.9]) #重新改变坐标刻度范围的需求 
# set #3 plot
plt.axes([0.55,0.1,.3,.3], frameon=True,fc="y",aspect="equal")
plt.plot(4+np.arange(3), [0,1,0], color="blue", linewidth=2, linestyle=":")

使用两种方法控制坐标轴刻度的显示

关于 matplotlib 中的控制坐标轴刻度显示的两种方法:

  • 一种方法是利用 matploblib 的面向对象的 Axes.set_xticks()和 Axes.set_yticks()实例方法,实现不画坐标轴刻度的需求;
  • 另一种方法是调用模块pyplot的API,使用函数setp()设置刻度元素( ticklabel和tickline),更新显示属性的属性值为 False;
#第一种
import matplotlib.pyplot as plt
ax1 = plt.subplot(121)
ax1.set_xticks(range(0,251,50))
plt.grid(True,axis="x")
ax2 = plt.subplot(122)
ax2.set_xticks([])
plt.grid(True,axis="x")

#第二种
import matplotlib.pyplot as plt
ax1 = plt.subplot(221)
plt.setp(ax1.get_xticklabels(),visible=True)
plt.setp(ax1.get_xticklines(),visible=True)
plt.grid(True,axis="x")

ax2 = plt.subplot(222)
plt.setp(ax2.get_xticklabels(),visible=True)
plt.setp(ax2.get_xticklines(),visible=False)
plt.grid(True,axis="x")

ax3 = plt.subplot(223)
plt.setp(ax3.get_xticklabels(),visible=False)
plt.setp(ax3.get_xticklines(),visible=True)
plt.grid(True,axis="x")

ax3 = plt.subplot(224)
plt.setp(ax3.get_xticklabels(),visible=False)
plt.setp(ax3.get_xticklines(),visible=False)
plt.grid(True,axis="x")
plt.show()
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(0.5,2*np.pi,20)
y = np.random.randn(20)
markerline,stemlines,baseline = plt.stem(x,y)
#stemlines 是实例列表,改变实例属性值应该使用函数 setp()来进行设置
plt.setp(markerline,color="chartreuse",marker="D")
plt.setp(stemlines,linestyle="-.")
baseline.set_linewidth(2)

去掉边框、刻度线等

ax1.spines["right"].set_color("none")  #去掉边框
ax1.spines["top"].set_color("none")

ax2.xaxis.set_ticks_position("bottom") #去掉顶部刻度线
ax3.yaxis.set_ticks_position("left") #去掉右边刻度线

改变坐标轴位置

# -*- coding:utf-8 -*-
import matplotlib as mpl
import matplotlib.pyplot as plt
import numpy as np
mpl.rcParams["font.sans-serif"]=["SimHei"]
mpl.rcParams["axes.unicode_minus"]=False
x = np.linspace(-2*np.pi,2*np.pi,200)
y = np.sin(x)
y1 = np.cos(x)
ax = plt.subplot(111)
ax.plot(x,y,ls="-",lw=2,label="$\sin(x)$")
ax.plot(x,y1,ls="-",lw=2,label="$\cos(x)$")
ax.legend(loc="lower left")
plt.title("$\sin(x)$"+"和"+"$\cos(x)$"+"函数")
# set xlimit
ax.set_xlim(-2*np.pi,2*np.pi)
# set ticks
plt.xticks([-2*np.pi,-3*np.pi/2,-1*np.pi,-1*(np.pi)/2,0,(np.pi)/2,np.pi,
3*np.pi/2,2*np.pi],
["$-2\pi$","$-3\pi/2$","$-\pi$","$-\pi/2$","$0$","$\pi/2$","$\pi$","$3\pi/2$","$2\pi$"])
ax.spines["right"].set_color("none")
ax.spines["top"].set_color("none")
ax.spines["bottom"].set_position(("data",0))
ax.spines["left"].set_position(("data",0))
'''
ax.spines 会调用轴脊字典,其中的键是轴脊位置, 如“top”“right”“bottom”“left”键值是
matplotlib.spines.Spine 对象,实例方法 set_position()就是对轴脊位置的控制方法,其中参数“data”
说明控制轴脊位置的坐标值与折线图的坐标系统一致。因此, 参数 0 就表示将底端轴脊移动到左侧轴脊的零点处
同理,将左侧轴脊移动到底端轴脊的零点处。
'''
ax.xaxis.set_ticks_position("bottom")
ax.yaxis.set_ticks_position("left")
plt.show()

第九章设置线条标记等

字体、线条、标记

#字体
font = {"family": "monospace","color":"maroon","weight":"bold","size":16}
ax.set_title("keyword mode is 'fontdict=font'",fontdict=font)
ax.set_xlabel("time (h)",**font)

#线条
linestyleList = ["-","--","-.",":"]
for i,ls in enumerate(linestyleList):
    ax.text(0,i+0.5,"'{}'".format(ls),**font)
    ax.plot(x,(i+0.5)*y,linestyle=ls,color=color,linewidth=linewidth)
    
#标记
msNameList = [  "'.'--point marker",
                "','--pixel marker",
                "'o'--circle marker",
                "'v'--triangle_down marker",
                "'^'--triangle_up marker",
                "'<'--triangle_left marker",
                "'>'--triangle_right marker",
                "'1'--tri_down marker",
                "'2'--tri_up marker",
                "'3'--tri_left marker",
                "'4'--tri_right marker",
                "'s'--square marker",
                "'p'--pentagon marker",
                "'*'--star marker",
                "'h'--hexagon1 marker",
                "'H'--hexagon2 marker",
                "'+'--plus marker",
                "'x'--x marker",
                "'D'--diamond marker",
                "'d'--thin_diamond marker",
                "'|'--vline marker",
                "'_'--hline marker"]
markerstyleList = ['.',',','o','v','^','<','>','1','2','3','4','s','p','*','h','H','+','x','D','d','|','_']
for i,ms in enumerate(markerstyleList):
    ax.text(0,i+0.5,msNameList[i],**font_style)
    ax.plot(x,(i+0.5)*y,marker=ms,**line_marker_style)
    
###自定义标记类型!!!!!好看
ax[0,0].scatter(x,y*1.5,marker=r"$\clubsuit$",c="#fb8072",s=500) #梅花
'''
marker=r"$\heartsuit$" #爱心
marker=r"$\diamondsuit$" %菱形
marker=r"$\spadesuit$" #红桃
'''

dashes控制点间隔,线长,间隔长

#10,2表示10个点是线,然后空2个点空白
ax.plot(x,y,dashes=[10,2],label="dashes=[10,2]",**line_marker_style1)
ax.plot(x,y+0.2,dashes=[3,1],label="dashes=[3,1]",**line_marker_style2)
ax.plot(x,y+0.4,dashes=[2,2,8,2],label="dashes=[2,2,8,2]",**line_marker_style3)

标记填充

fillstyleList = ["full","left","right","bottom","top","none"]
x = np.arange(3,11,1)
y = np.linspace(1,1,8)
ax.text(4,6.5,"fill styles",**font_style)
for i,fs in enumerate(fillstyleList):
    ax.text(0,i+0.4,"'{}'".format(fs),**font_style)
    ax.plot(x,(i+0.5)*y,fillstyle=fs,**line_marker_style)