在工作中常使用python绘制各类图形,之前通过CSDN学习到了很多,现在在这里对各类绘图工具及用法做一个总结,我将附上代码以及图片效果,以方便大家使用python进行图片绘制。需要注意一下,代码中的数据部分要用上自己处理的结果。
第一步我们导入包matplotlib,才有了后面各种图片绘制的基础
import matplotlib
1.折线图,比较简单,需要注意的是对横坐标数目太多的精简化处理。
效果展示:
代码如下:
figsize = 18,10
figure, ax = plt.subplots(figsize=figsize)
plt.title('折线图',fontsize=20,y=1.02)
plt.plot(timestamp, fcurve, color='#27547b', label='变量1')
plt.plot(timestamp, bcurve, color='#c09c69', label='变量2')
plt.legend(fontsize=15)
plt.xticks(timestamp, rotation=30) #横坐标设置30度角
plt.tick_params(labelsize=15)
labels = ax.get_xticklabels() + ax.get_yticklabels()
[label.set_fontname('Times New Roman') for label in labels] #设置坐标轴字体为Times New Roman
plt.gca().xaxis.set_major_locator(ticker.MultipleLocator(len(timestamp)/15)) #横坐标数目过多的精简化处理
plt.show()
2.多变量柱状图,一个横坐标对应两个纵坐标柱子
效果展示:
代码如下:
month_label = [i[2:7] for i in month] #月份坐标
x =list(range(len(month_label)))
total_width, n = 0.8, 2
width = total_width / n
figsize = 18,10
figure, ax = plt.subplots(figsize=figsize)
plt.title('多变量柱状图',fontsize=20,y=1.05)
plt.bar(x, f_monthly, width=width, label='变量1',fc = '#27547b')
for i in range(len(x)):
x[i] = x[i] + width
plt.bar(x, e_monthly, width=width, label='变量2',tick_label = month_label,fc = '#c09c69')
plt.xticks(x, rotation=60)
plt.tick_params(labelsize=15)
labels = ax.get_xticklabels() + ax.get_yticklabels()
[label.set_fontname('Times New Roman') for label in labels]
plt.ylabel("纵坐标变量",fontsize=20)
plt.legend(fontsize=15)
plt.show()
带有负向坐标的柱状图,效果如下:
代码如下:
font1 = {'family': 'Times New Roman',
'weight': 'normal',
'size': 20}
figsize = 12,8
figure, ax = plt.subplots(figsize=figsize)
plt.title('柱状图2', fontsize=15,y=1.05)
width = 15
plt.bar(timelist, r_list, width=width, color='#27547b')
for a, b in zip(timelist, r_list):
if(b>0):
plt.text(a, b, '%.2f' % b, ha='center', va='bottom', fontsize=12, fontdict=font1) #调整数字位置
else:
plt.text(a, b, '%.2f' % b, ha='left', va='top', fontsize=12, fontdict=font1)
ax.set_ylim(-5, 30) #设置坐标轴范围
#边框处理
ax.spines['right'].set_color('none')
ax.spines['top'].set_color('none')
ax.xaxis.set_ticks_position('bottom')
ax.spines['bottom'].set_position(('data',0))
#坐标轴处理
plt.xticks(timelist, rotation=30)
plt.tick_params(labelsize=12)
labels = ax.get_xticklabels() + ax.get_yticklabels()
[label.set_fontname('Times New Roman') for label in labels]
plt.show()
3.百分比堆积图,在一个柱状图中进行百分比的分割
效果展示:
代码如下:
pd_style.fillna(0,inplace=True)
# 把pandas转化为numpy
np_style = np.array(pd_style).tolist()
np_growth = np_style[0][1:]
np_balance = np_style[1][1:]
np_value = np_style[2][1:]
fig, ax = plt.subplots(figsize=(12,8))
ax.spines['right'].set_visible(False)
ax.spines['top'].set_visible(False)
plt.title('百分比堆积图', fontsize=15,y=1.08)
labels = time_list
data = [np_growth,np_balance,np_value]
# 多柱子加tag方法
tags=[ '类别1','类别2','类别3']
colors=['#27547b','#c09c69','#dbdcdc']
x = range(len(labels))
width = 0.15
# 将bottom_y元素都初始化为0
bottom_y = [0] * len(labels)
# 计算每组柱子的总和,为计算百分比做准备
sums = [sum(i) for i in zip(np_growth,np_balance,np_value)]
for i in range(len(data)):
# 计算每个柱子的高度,即百分比
y = [a/b for a, b in zip(data[i], sums)]
plt.bar(x, y, width, bottom=bottom_y,label=tags[i],color=colors[i])
# 计算bottom参数的位置
bottom_y = [(a+b) for a, b in zip(y, bottom_y)]
plt.ylabel("比例",fontsize=15)
plt.xticks(x, labels, rotation=30)
plt.tick_params(labelsize=15)
labels = ax.get_xticklabels() + ax.get_yticklabels()
[label.set_fontname('Times New Roman') for label in labels]
plt.legend(bbox_to_anchor=(0.5,1.05), loc='center',ncol=3)
plt.show()
4.分段折线图,在折线图的不同分位数区间,使用不同的颜色
效果展示:
代码如下:
首先,导入俩包
from matplotlib.collections import LineCollection
from matplotlib.colors import ListedColormap, BoundaryNorm
num = len(time_end)
dt = [i for i in range(num)]
x = np.array(dt)
y = res
dydx = y
points = np.array([x, y]).T.reshape(-1, 1, 2)
segments = np.concatenate([points[:-1], points[1:]], axis=1)
figsize = 15,8
fig, axs = plt.subplots(figsize=figsize)
plt.title('分段折线图',fontsize=20,y=1.05)
cmap = ListedColormap(['#27547b','#c09c69','#7ea1b8','lightcoral'])
norm = BoundaryNorm([0, 25, 50, 75, 100], cmap.N)
lc = LineCollection(segments, cmap=cmap, norm=norm)
lc.set_array(dydx)
lc.set_linewidth(2)
line = axs.add_collection(lc)
# 最右的colorbar
cb = fig.colorbar(line, ax=axs)
cb.ax.tick_params(labelsize=15)
for l in cb.ax.yaxis.get_ticklabels():
l.set_family("Times New Roman")
axs.set_xlim(x.min(), x.max())
axs.set_ylim(-0, 100)
tik = [0,int(num/4),2*int(num/4),3*int(num/4),num-1]
plt.xticks(tik,[time_end[tik[0]], time_end[tik[1]], time_end[tik[2]], time_end[tik[3]], time_end[tik[4]]], rotation=30)
plt.tick_params(labelsize=15)
labels = axs.get_xticklabels() + axs.get_yticklabels()
[label.set_fontname('Times New Roman') for label in labels]
plt.ylabel("百分位数(%)",fontsize=18,labelpad=20)
plt.show()
5.扇形图
效果展示:
代码如下:
length = 8
labels = ['类别'+str(i+1) for i in range(length]
sizes= np.random.rand(length).tolist()
colors=['#27547b','#c09c69','#dbdcdc','#7ea1b8','#a1b1b9',
'#a7d4d7','#f2f2f2','lightblue','lemonchiffon','lavender']
explode=0.1,0.05,0.15,0.2,0.15,0.15,0.25,0.27,0.3,0.35
plt.figure(figsize=(12,8))
patches,l_text,p_text = plt.pie(sizes,
explode=explode[:length],
labels=labels,
colors=colors[:length],
autopct='%1.1f%%',
shadow=True,
startangle=100
)
for t in l_text:
t.set_size(18)
for t in p_text:
t.set_size(15)
plt.axis('equal')
plt.legend(labels,title='类别',loc='upper left')
plt.title(timestock[j]+" 分布", fontsize=20,y=1.05)
plt.show()
6.堆积折线图,之前找了好久才找到这种图的名称;国内似乎用的不多,用于描述多变量的百分比关系。
效果展示:
代码如下:
# 六个类别的数据
y1p = res_list[0]
y2p = res_list[1]
y3p = res_list[2]
y4p = res_list[3]
y5p = res_list[4]
y6p = res_list[5]
figsize = 15,10
figure, ax = plt.subplots(1,figsize=figsize)
plt.title(title,fontsize=20,y=1.1)
# 比例堆积柱状图
plt.stackplot(x, y1p, y2p, y3p, y4p, y5p, y6p, baseline='zero', labels=tags,
colors=['#27547b','#c09c69','#dbdcdc','#7ea1b8','lightblue','lemonchiffon'])
# 显示范围
plt.xlim(0, len(x))
plt.ylim(0, 1)
plt.xticks(x, rotation=30)
plt.tick_params(labelsize=12)
labels = ax.get_xticklabels() + ax.get_yticklabels()
[label.set_fontname('Times New Roman') for label in labels]
plt.gca().xaxis.set_major_locator(ticker.MultipleLocator((len(x)/10)))
# 添加图例
plt.legend(bbox_to_anchor=(0.5,1.05), loc='center',ncol=3,fontsize=12)
plt.show()
plt.savefig(root+fundid+'/basic_info/'+title+'.jpg')
7.坐标轴的调整
1)设置横坐标的旋转角度:plt.xticks(x, rotation=30)
2)设置横坐标字体大小:plt.tick_params(labelsize=12)
3)设置横纵坐标字体样式:labels = ax.get_xticklabels() + ax.get_yticklabels()
[label.set_fontname('Times New Roman') for label in labels]
4)调整横坐标显示数量,代码显示10%的数目:plt.gca().xaxis.set_major_locator(ticker.MultipleLocator((len(x)/10)))
8.图例及图片保存时的调整
1)调整图例为横向展示,每行4个:plt.legend(bbox_to_anchor=(0.5,1.05), loc='center',ncol=4,fontsize=12)
效果如下:
2)设置图例的内容及位置:plt.legend(labels,title='行业名称',loc='upper left')
3)保存图片时,去掉图片周围的留白:plt.savefig(root +'/curve_analysis.jpg', bbox_inches='tight', pad_inches=0)
以上就是全部的图以及对应的代码,后面还会根据需要继续补充,也欢迎大家一起交流学习!