今天主要講一下get到的一些小技能刷钢,包括:
- 當(dāng)坐標(biāo)軸標(biāo)簽太長串绩,出框的時(shí)候室琢,自動(dòng)調(diào)整子圖——語句:
plt.tight_layout()
- 自動(dòng)調(diào)整text(文本標(biāo)簽)的位置遮糖,避免重疊——調(diào)包:
adjustText
(具體文檔見adjustText文檔) - 調(diào)用已有的顏色主題麻汰;Choosing Colormaps in Matplotlib
import matplotlib.pyplot as plt
import matplotlib
import numpy as np
import matplotlib.transforms as mtransforms
from matplotlib.ticker import FuncFormatter
from adjustText import adjust_text
from matplotlib import cm
#設(shè)置字體速客、圖形樣式
matplotlib.rcParams['font.sans-serif'] = ['SimHei']
matplotlib.rcParams['font.family']='sans-serif'
matplotlib.rcParams['axes.unicode_minus'] = False
# 顏色轉(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進(jìn)制拼接轉(zhuǎn)換并大寫
strs += str(hex(num))[-2:].replace('x','0').upper()
return strs
1.左右條形圖(left_right_barh)
def left_right_barh(fig,subplotid,ylabel,values1,values2,label1,label2,textformat,withlegend=1,category=0,filename=0):
values1=[0-i for i in values1]
# 倒序
ylabel,values1,values2=ylabel[::-1],values1[::-1],values2[::-1]
# 作圖
ax=fig.add_subplot(subplotid)
barh1=ax.barh(ylabel,width=values1,label=label1)
barh2=ax.barh(ylabel,width=values2,label=label2)
# 去掉邊框
orientation=['top','bottom','right']
for o in orientation:
ax.spines[o].set_visible(False)
# 去掉xticks
ax.set_xticks(())
# 圖例
if withlegend:
ax.legend(ncol=2, bbox_to_anchor=(0.5, -0.1),edgecolor='w',
loc='lower center', fontsize='small')
# y軸標(biāo)題
if category:
ax.set_ylabel(category)
# 添加barh的數(shù)據(jù)標(biāo)簽
texts=[]
for b in barh1:
texts.append(ax.text(b.get_width()-0.04,b.get_y()+b.get_height()/3,
format(-b.get_width(),textformat),va="center",ha='left'))
for b in barh2:
texts.append(ax.text(b.get_width(),b.get_y()+b.get_height()/3,
format(b.get_width(),textformat),va="center",ha='right'))
adjust_text(texts,only_move={'points':'x', 'text':'x', 'objects':'x'}) #避免y軸上的調(diào)整
plt.tight_layout()#調(diào)整子圖溺职,避免標(biāo)簽出框,自動(dòng)調(diào)整的語句,圖則會(huì)自動(dòng)調(diào)整標(biāo)簽大小
if filename:
plt.savefig(filename,dpi=600)
return ax
def left_right_barh_ex():
# 數(shù)據(jù)
ylabel=["不識(shí)字或識(shí)字很少","小學(xué)","初中","普通高中","中等職業(yè)/技術(shù)/師范學(xué)校","高職/大專","本科","研究生","博士"]
values1=[0.0477,0.2013,0.2751,0.128,0.0774,0.1219,0.1244,0.0172,0.007]
values2=[0.0196,0.1405,0.2834,0.1577,0.0597,0.1275,0.1698,0.0299,0.0119]
textformat='.2%'
fig=plt.figure()
left_right_barh(fig,111,ylabel=ylabel,values1=values1,values2=values2,
label1='母親',label2='父親',filename="left_right_barh.png",textformat=textformat)
plt.show()
left_right_barh_ex()
- 若不加
plt.tight_layout()
的效果如下位喂,可以看到辅愿,縱坐標(biāo)標(biāo)簽太長已經(jīng)出去了。
- 若不加
adjust_text(texts,only_move={'points':'x', 'text':'x', 'objects':'x'})
的效果如下忆某,可以看到点待,數(shù)據(jù)標(biāo)簽擠在一起了。
adjustText
這個(gè)包在做散點(diǎn)圖進(jìn)行數(shù)據(jù)標(biāo)簽添加時(shí)弃舒,應(yīng)該是最有用的癞埠,文檔中的例子如下:
2.簡單柱狀圖(simple_bar)
def simple_bar(xlabel,value,colorname,filename):
# 系列顏色選取
colorname=cm.get_cmap(name=colorname)
color=colorname(value)
fig=plt.figure()
ax=fig.add_subplot()
bar=ax.bar(xlabel,value,color=color)
# 去掉邊框
orientation=['top','left','right']
for o in orientation:
ax.spines[o].set_visible(False)
# 去掉xticks
ax.set_yticks(())
# 文本標(biāo)簽
for b in bar:
ax.text(b.get_x()+b.get_width()/2,b.get_height()+0.01,
format(b.get_height(),'.2%'),va="center",ha='center')
plt.savefig(filename,dpi=600)
plt.show()
def simple_bar_ex1():
xlabel=["5萬元以下", "5萬-10萬", "11萬-20萬", "21萬-40萬", "41萬以上"]
value=[0.3417, 0.3095, 0.2272, 0.0858, 0.0359]
simple_bar(xlabel,value,colorname='coolwarm',filename='simple_bar1.png')
這里用的colorname是”coolwarm”状原,改一下這個(gè)colorname為“Pastel1”,效果如下:
現(xiàn)有的主題顏色有: