上次用pyecharts畫了地圖,【python實戰(zhàn)】 pyecharts繪制地圖
雖然很好看牢屋,但是且预,考慮到渲染成圖片時間比較長,因此烙无,要是要批量作圖的話锋谐,還是用matplotlib比較好,就像之前的Python批量word報告(帶圖)【思路篇】
截酷,也是用的matplotlib涮拗。
matplotlib算是很底層的包了,好處在于個性化設(shè)置上更靈活迂苛,缺點可能是要寫的代碼更多些吧三热,但是,總的來說灾部,瑕不掩瑜康铭。
在學(xué)著用matplotlib作圖的時候,主要是看matplotlib(https://matplotlib.org/index.html)里面的例子以及相應(yīng)的文檔赌髓。但不得不說从藤,里面的文檔真的挺難看的,pyecharts的就好看多了锁蠕。另外就是加上搜索引擎了夷野。
這里放兩個最近用到的圖。
1.條形圖(broken_barh)
import matplotlib.pyplot as plt
import matplotlib
import matplotlib.lines as lines
# 顏色轉(zhuǎn)換
def RGB_to_Hex(tmp):
rgb = tmp.split(',')#將RGB格式劃分開來
strs = '#'
for i in rgb:
num = int(i)#將str轉(zhuǎn)int
#將R荣倾、G悯搔、B分別轉(zhuǎn)化為16進制拼接轉(zhuǎn)換并大寫
strs += str(hex(num))[-2:].replace('x','0').upper()
return strs
#設(shè)置字體、圖形樣式
# sns.set_style("whitegrid")
matplotlib.rcParams['font.sans-serif'] = ['SimHei']
matplotlib.rcParams['font.family']='sans-serif'
matplotlib.rcParams['axes.unicode_minus'] = False
# 數(shù)據(jù)
data={
"data": [
{"name":'全省',"5pct": 354, "mean":500,"95pct":684},
{"name":'全市',"5pct": 342, "mean":511,"95pct":668},
{"name":'A縣', "5pct": 327, "mean":514,"95pct":661}
],
}
# 數(shù)據(jù)設(shè)置
ylabel=[d["name"] for d in data['data']]
pct5=[d["5pct"] for d in data['data']]
pct95=[d["95pct"] for d in data['data']]
mean=[d["mean"] for d in data['data']]
xbar=[(d["5pct"],d["95pct"]-d["5pct"]) for d in data['data']]
# 屬性設(shè)置
yticks=[5,10,15]
xlim=(min(pct5)-100,max(pct95)+100)
colors=[RGB_to_Hex('255,140,0'),RGB_to_Hex('107,142,35'),RGB_to_Hex('116,162,221')]
barheight=2
# 作圖
# 設(shè)置圖形大小
plt.rcParams['figure.figsize'] = (6,2.5)
fig, ax = plt.subplots()
for i in range(len(xbar)):
ax.broken_barh([xbar[i]],(4+i*5,barheight),facecolors=(colors[i]))
# 加標(biāo)簽
ax.text(pct5[i]-40,yticks[i]-0.2,str(pct5[i]),size=10)
ax.text(pct95[i]+10,yticks[i]-0.2,str(pct95[i]),size=10)
ax.text(mean[i]-30,yticks[i]-0.2,str(mean[i]),size=10,color='black')
# 加豎線
line = lines.Line2D([mean[i],mean[i]], [4+i*5,4+i*5+barheight],
lw=1, color='black', axes=ax)
ax.add_line(line)
# 去掉邊框
ax.spines['top'].set_visible(False)
ax.spines['right'].set_visible(False)
#設(shè)置x軸取值范圍舌仍,y軸間隔及標(biāo)簽
ax.set_xlim(xlim)
ax.set_yticks(yticks)
ax.set_yticklabels(ylabel)
plt.savefig("broken_barh.png",dpi=600,bbox_inches = 'tight')
plt.show()
2.散點圖(scatter)
import matplotlib.pyplot as plt
import matplotlib
import matplotlib.lines as lines
from matplotlib.ticker import FuncFormatter
# 顏色轉(zhuǎn)換
def RGB_to_Hex(tmp):
rgb = tmp.split(',')#將RGB格式劃分開來
strs = '#'
for i in rgb:
num = int(i)#將str轉(zhuǎn)int
#將R妒貌、G、B分別轉(zhuǎn)化為16進制拼接轉(zhuǎn)換并大寫
strs += str(hex(num))[-2:].replace('x','0').upper()
return strs
#設(shè)置字體铸豁、圖形樣式
# sns.set_style("whitegrid")
matplotlib.rcParams['font.sans-serif'] = ['SimHei']
matplotlib.rcParams['font.family']='sans-serif'
matplotlib.rcParams['axes.unicode_minus'] = False
# 數(shù)據(jù)(太多了灌曙,就只放三條吧)
data={
"data": [
{"校間差異":0.135311972763609,"全省其他縣":0,"你市各縣":577.362102747501,"你市":0},
{"校間差異":0.0616036942022612,"全省其他縣":0,"你市各縣":546.788848220486,"你市":0},
{"校間差異":0.209066958823479,"全省其他縣":0,"你市各縣":517.929672671431,"你市":0}
}
# 數(shù)據(jù)設(shè)置
x=[d["校間差異"] for d in data['data']]
y1=[d["全省其他縣"] for d in data['data'] ]
y2=[d["你市各縣"] for d in data['data']]
y3=[d["你市"] for d in data['data']]
label=["全省其他縣","你市各縣","你市"]
# 作圖
# 設(shè)置圖形大小
plt.rcParams['figure.figsize'] = (8,6)
fig, ax = plt.subplots()
ax.scatter(x,y1,c=RGB_to_Hex('79,129,189'),label=label[0])
ax.scatter(x,y2,c=RGB_to_Hex('0,176,80'),label=label[1])
ax.scatter(x,y3,c=RGB_to_Hex('228,108,10'),marker='^',label=label[2])
# 去掉邊框
ax.spines['top'].set_visible(False)
ax.spines['right'].set_visible(False)
#添加圖例
ax.legend(loc=9,ncol=3,edgecolor='grey',bbox_to_anchor=(0.5,1.1))
#設(shè)置y軸取值范圍
ylim=[400,600]
xlim=[0,0.4]
ax.set_ylim(ylim)
ax.set_xlim(xlim)
# x軸以百分比的形式呈現(xiàn)
def to_percent(temp, position):
return '%.2f'%(10*temp) + '%'
plt.gca().xaxis.set_major_formatter(FuncFormatter(to_percent))
# 添加x和y軸名稱
ax.set_xlabel('校間差異',weight='bold',size=12)
ax.set_ylabel('語文成績',weight='bold',size=12,rotation='vertical')
# 加虛線
linecolor=RGB_to_Hex('79,129,189')
linestyle='--'
line_pos=[0.1,0.2,450,550]
for i in range(2):
line = lines.Line2D([line_pos[i],line_pos[i]],ylim,lw=0.5, color=linecolor, axes=ax,linestyle=linestyle)
ax.add_line(line)
for i in range(2,4):
line = lines.Line2D(xlim,[line_pos[i],line_pos[i]],lw=0.5, color=linecolor, axes=ax,linestyle=linestyle)
ax.add_line(line)
# 添加文本
ax.text(0,ylim[1]-10,'校間差異小,\n語文成績高',size=12,color=RGB_to_Hex('79,129,189'),fontweight='bold')
ax.text(0,ylim[0]+10,'校間差異小节芥,\n語文成績低',size=12,color='red',fontweight='bold')
ax.text(xlim[1]-0.04,ylim[0]+10,'校間差異大在刺,\n語文成績低',size=12,color='red',fontweight='bold')
ax.text(xlim[1]-0.04,ylim[1]-10,'校間差異大逆害,\n語文成績高',size=12,color='red',fontweight='bold')
plt.savefig("scatter.png",dpi=600,bbox_inches = 'tight')
plt.show()