今天主要讲一下get到的一些小技能,包括:
- 当坐标轴标签太长,出框的时候,自动调整子图——语句:
plt.tight_layout()
- 自动调整text(文本标签)的位置,避免重叠——调包:
adjustText
(具体文档见adjustText文档) - 调用已有的颜色主题;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
#设置字体、图形样式
matplotlib.rcParams['font.sans-serif'] = ['SimHei']
matplotlib.rcParams['font.family']='sans-serif'
matplotlib.rcParams['axes.unicode_minus'] = False
# 颜色转换
def RGB_to_Hex(tmp):
rgb = tmp.split(',')#将RGB格式划分开来
strs = '#'
for i in rgb:
num = int(i)#将str转int
#将R、G、B分别转化为16进制拼接转换并大写
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轴标题
if category:
ax.set_ylabel(category)
# 添加barh的数据标签
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轴上的调整
plt.tight_layout()#调整子图,避免标签出框,自动调整的语句,图则会自动调整标签大小
if filename:
plt.savefig(filename,dpi=600)
return ax
def left_right_barh_ex():
# 数据
ylabel=["不识字或识字很少","小学","初中","普通高中","中等职业/技术/师范学校","高职/大专","本科","研究生","博士"]
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()
的效果如下,可以看到,纵坐标标签太长已经出去了。
- 若不加
adjust_text(texts,only_move={'points':'x', 'text':'x', 'objects':'x'})
的效果如下,可以看到,数据标签挤在一起了。
adjustText
这个包在做散点图进行数据标签添加时,应该是最有用的,文档中的例子如下:
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(())
# 文本标签
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”,改一下这个colorname为“Pastel1”,效果如下:
现有的主题颜色有: