matplotlib
01 | 调参
1.fig,ax
# 2,2代表2x2
fig,ax = plt.subplots(nrows=2, ncols=2,figsize = (12,5))
['df'].value_counts().plot(kind='pie',autopct='%1.2f%%',explode=(0.1,0),ax = ax[0,0],labels = ['男','女'])
ax[0,0].set_title('title_name')
ax[0,0].set_ylabel('') # 删除左侧标签
plt.show()
2.显示中文 / 负号plt.rcParams[ ]
sns.set_style('whitegrid',{'font.sans-serif':['simhei','Arial']})
plt.rcParams['font.sans-serif'] = ['SimHei'] # 显示中文
plt.rcParams['axes.unicode_minus']=False # 显示负号
3. 修改plt.xticks() / plt.xlim()
import matplotlib.pyplot as plt
plt.xticks(range(0,20,2))
plt.yticks(range(20,40,4))
plt.show()
import matplotlib.pyplot as plt
plt.xticks(range(0,20,2))
plt.yticks(range(20,40,4))
plt.ylim(20,40) #plt.yticks定义数据区间,plt.ylim定义刻度
plt.show()
4.修改style plt.style.use()
5.查看style plt.style.available
设置matplotlib可以使用的风格
02 | 可视化
1.plt.bar( )
import matplotlib.pyplot as plt
import numpy as np
a = np.linspace(1,10,10)
b = np.linspace(1,10,10)
label = []
for i in ('ABCDEFGHIJ'):
label.append(i)
plt.bar(a,b,tick_label = label)
plt.show()
2.plt.barh(a,b,tick_label = label)
import matplotlib.pyplot as plt
import numpy as np
a = np.linspace(1,10,5)
b = np.linspace(1,5,5)
label_bath = ['a','b','c','d','e']
# plt.barh()可以在y轴上画柱状图,tick_label对应柱状图的值
plt.barh(a,b,tick_label = label_bath)
plt.show()
3.堆积图
import matplotlib.pyplot as plt
plt.style.use('seaborn-colorblind')
# 构造数据,统计四个季度app端男女用户数量(万)
labels = ['S1','S2','S3','S4']
men_means = [20, 35, 30, 35]
women_means = [25, 32, 34, 20]
# 调matplotlib参数
width = 0.2 # the width of the bars: can also be len(x) sequence
fig, ax = plt.subplots(figsize=(5,3),dpi=200)
men_data = ax.bar(labels, men_means, width,label='Men')
women_data = ax.bar(labels, women_means, width, bottom=men_means,label='Women')
ax.set_title('Scores by group and gender')
ax.legend()
def auto_text(rects):
for rect in rects:
ax.text(rect.get_x(), rect.get_height(), rect.get_height(), ha='left', va='bottom')
auto_text(men_data)
auto_text(women_data)
plt.show()