畫柱狀圖時(shí)會遇到添加顯著性標(biāo)記的問題春霍,因?yàn)閙atplotlib沒有自帶的接口,所以只好自己畫了一個(gè)
主要思路是用plot畫標(biāo)注框線焦履,用annotate標(biāo)注掸掸。
具體應(yīng)用的時(shí)候需要根據(jù)柱狀圖的位置,調(diào)整x和y的坐標(biāo)
import numpy as np #使用import導(dǎo)入模塊numpy纪蜒,并簡寫成np
import matplotlib.pyplot as plt #使用import導(dǎo)入模塊matplotlib.pyplot,并簡寫成plt
plt.figure(figsize=(8,4)) #設(shè)置繪圖對象的寬度和高度
from PIL import Image
from pylab import *
mpl.rcParams['font.sans-serif'] = ['SimHei'] #指定默認(rèn)字體
mpl.rcParams['axes.unicode_minus'] = False #解決保存圖像是負(fù)號'-'顯示為方塊的問題
x = np.ones((4))
y = np.arange(0.7,1.0,0.1)
plt.plot(x,y,label="$y$",color="black",linewidth=1)
x = np.arange(1,3.1,0.1)
y = 1+0*x
plt.plot(x,y,label="$y$",color="black",linewidth=1)
x0 = 2
y0=1
plt.annotate(r'$***$', xy=(x0, y0), xycoords='data', xytext=(-15, +1),
textcoords='offset points', fontsize=16,color="red")
x = np.ones((4))*3
y = np.arange(0.7,1.0,0.1)
plt.plot(x,y,label="$y$",color="black",linewidth=1)
plt.ylim(0,2) #使用plt.ylim設(shè)置y坐標(biāo)軸范圍
plt.xlim(-1,5)
plt.xlabel("隨便畫畫") #用plt.xlabel設(shè)置x坐標(biāo)軸名稱
'''設(shè)置圖例位置'''
plt.grid(True)
plt.show()
結(jié)果示意
示意圖
將代碼改寫成函數(shù)此叠,方便復(fù)用
def plot_sig(xstart,xend,ystart,yend,sig):
x = np.ones((2))*xstart
y = np.arange(ystart,yend,yend-ystart-0.1)
plt.plot(x,y,label="$y$",color="black",linewidth=1)
x = np.arange(xstart,xend+0.1,xend-xstart)
y = 1+0*x
plt.plot(x,y,label="$y$",color="black",linewidth=1)
x0 = (xstart+xend)/2
y0=yend
plt.annotate(r'%s'%sig, xy=(x0, y0), xycoords='data', xytext=(-15, +1),
textcoords='offset points', fontsize=16,color="red")
x = np.ones((2))*xend
y = np.arange(ystart,yend,yend-ystart-0.1)
plt.plot(x,y,label="$y$",color="black",linewidth=1)
plt.ylim(0,2) #使用plt.ylim設(shè)置y坐標(biāo)軸范圍
plt.xlim(-1,5)
plt.xlabel("隨便畫畫") #用plt.xlabel設(shè)置x坐標(biāo)軸名稱
'''設(shè)置圖例位置'''
plt.grid(True)
plt.show()
plot_sig(1,3.0,0.8,1.1,'***')
將函數(shù)的參數(shù)都改成列表纯续,使可以同時(shí)呈現(xiàn)不同數(shù)據(jù)之間比較的結(jié)果
def plot_sig(xstart,xend,ystart,yend,sig):
for i in range(len(xstart)):
x = np.ones((2))*xstart[i]
y = np.arange(ystart[i],yend[i],yend[i]-ystart[i]-0.1)
plt.plot(x,y,label="$y$",color="black",linewidth=1)
x = np.arange(xstart[i],xend[i]+0.1,xend[i]-xstart[i])
y = yend[i]+0*x
plt.plot(x,y,label="$y$",color="black",linewidth=1)
x0 = (xstart[i]+xend[i])/2
y0=yend[i]
plt.annotate(r'%s'%sig, xy=(x0, y0), xycoords='data', xytext=(-15, +1),
textcoords='offset points', fontsize=16,color="red")
x = np.ones((2))*xend[i]
y = np.arange(ystart[i],yend[i],yend[i]-ystart[i]-0.1)
plt.plot(x,y,label="$y$",color="black",linewidth=1)
plt.ylim(0,math.ceil(max(yend)+4)) #使用plt.ylim設(shè)置y坐標(biāo)軸范圍
# plt.xlim(math.floor(xstart)-1,math.ceil(xend)+1)
#plt.xlabel("隨便畫畫") #用plt.xlabel設(shè)置x坐標(biāo)軸名稱
'''設(shè)置圖例位置'''
#plt.grid(True)
plt.show()
plot_sig([0.42,1.42],[1.42,2.42],[30,20],[30.8,20.8],'***')
加上柱狀圖,結(jié)果如下
示意圖
原創(chuàng)灭袁,轉(zhuǎn)載請注明出處