【python实战】matplotlib绘图(四)
2020-05-17 本文已影响0人
Hobbit的理查德
今天画的是些简单的图,简单线形图、雷达图和词云图。
同样地,先调包,设置整体字体和图形样式:
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
matplotlib.rcParams['axes.spines.top'] = False
matplotlib.rcParams['axes.spines.right'] = False
1.简单线形图(simple_plot)
simple_plot_ex1.pngdef simple_plot(xlabel,value,linestyle,filename):
fig=plt.figure(figsize=(7,4))
ax=fig.add_subplot()
ax.plot(xlabel,value,linestyle=linestyle)
ax.set_xticklabels(xlabel,rotation=20)
# 去掉边框
orientation=['top','left','right']
for o in orientation:
ax.spines[o].set_visible(False)
# 去掉xticks
ax.set_yticks(())
# 添加文本
texts = [plt.text(xlabel[i], value[i], format(value[i],'.2f')) for i in range(len(xlabel))]
adjust_text(texts)
plt.tight_layout()
plt.savefig(filename,dpi=600)
plt.show()
# 每行n字设置
def add_newline(str,num):
n=len(str)//4
newstr=''
if len(str)%4==0:
for i in range(n):
newstr=newstr+str[i*num:(i+1)*num]+'\n'
else:
for i in range(n+1):
newstr=newstr+str[i*num:(i+1)*num]+'\n'
return newstr
def simple_plot_ex1():
xlabel=["校园教学硬件设施","课程选修制度","成绩评定制度","评奖评优制度","学生参与学校相关教育教学管理事务","心理咨询服务",
"职业规划与就业指导","医学伦理与职业素养教育",
"社团和文体活动","对所在专业教育教学质量的总体评价","对所在大学教育教学质量的总体评价"]
xlabel=[add_newline(x,4) for x in xlabel]
value=[3.720057,3.594829,3.75914,3.675722,3.538275,
3.587154,3.511715,3.818522,3.719047,3.904868,3.919511]
simple_plot(xlabel,value,linestyle='--',filename='simple_plot_ex1.png')
# 调用
simple_plot_ex1()
同样是用plot
,进行相应的设置,就可以画出如下效果图:
def float_plot(label,value,filename):
marker_radius=3.3
markeredgewidth=2
fig=plt.figure()
ax=fig.add_subplot()
plot=ax.plot(label,value,
linewidth=0,
marker='o',
markeredgewidth=markeredgewidth,
markersize=np.pi*marker_radius**2,
markerfacecolor='w'
)
for x,y in zip(label,value):
ax.text(x,y,format(y,'.2f'),ha='center',va='center')
ax.set_ylim([3,4])
xpos=ax.get_xticks()
ypos=ax.get_yticks()
for i in range(len(value)):
line=lines.Line2D([xpos[i],xpos[i]],[ax.set_ylim()[0],value[i]-(marker_radius+markeredgewidth)/72],
linestyle='-.',linewidth=1)
ax.add_line(line)
plt.tight_layout()
plt.savefig(filename,dpi=600)
def float_plot_ex():
label=['过程性参与','主动性参与','规则性参与']
value=[3.22,3.50,3.89]
float_plot(label,value,'float_plot.png')
# 调用
float_plot_ex()
2.简单雷达图(simple_radar)
simple_radar1.pngdef simple_radar(label,valuels,tag,colorname,filename):
label.append(label[0])
value=[]
for v in valuels:
firstvalue=v[0]
v.append(firstvalue)
value.append(v)
angles=np.linspace(0, 2*np.pi, len(label)-1, endpoint=False)
angles=np.concatenate((angles, [angles[0]]))
colorname=cm.get_cmap(name=colorname)
fillalpha=list(np.linspace(0.2, 1, len(value), endpoint=False))
fillalpha=fillalpha[::-1]
print(fillalpha)
fig=plt.figure()
ax=fig.add_subplot(111,polar=True)
for i in range(len(value)):
fillcolorls=colorname(i)
ax.plot(angles,value[i],'--',color=fillcolorls,label=tag[i],linewidth=1)
ax.fill(angles,value[i],facecolor=fillcolorls,alpha=fillalpha[i])
ax.set_thetagrids(angles * 180/np.pi, label)
ax.set_theta_zero_location('N')#设置极坐标的起点(即0度)在正上方向
ax.set_ylim(min(min(value))-0.1,max(max(value))+0.1)
ax.legend(ncol=len(value), bbox_to_anchor=(0.5, -0.1),edgecolor='w',
loc='lower center', fontsize='small')
plt.savefig(filename,dpi=600)
plt.tight_layout()
plt.show()
def simple_radar_ex1():
label=["集体主义", "理想尊严至上","社会公正与正义","遵循社会道德","恪守学术道德"]
valuels=[[1.94,2.22,2.37,2.59,2.66],[1.8,2.29,2.44,2.62,2.65],
[2.02,2.3,2.4,2.57,2.55],[2.03,2.27,2.38,2.57,2.55]]
tag=['直辖市','东部','中部','西部']
simple_radar(label,valuels,colorname='Pastel1',tag=tag,filename='simple_radar1.png')
# 调用
simple_radar_ex1()
3.词云图(wordcloud)
wordcloud.pngdef wc(backpic,txt,picname):
backpic=imageio.imread(backpic)
w=wordcloud.WordCloud(scale=0.8,background_color='white',
# max_words=300,
mask=backpic,
max_font_size=80,
font_path='msyh.ttc',
random_state=30)
w.generate(' '.join(jieba.lcut(txt)))
w.to_file(picname)
return picname
def wc_ex():
txt='会议强调,要在做好常态化疫情防控的前提下,继续围绕重点产业链、龙头企业、重大投资项目,打通堵点、连接断点,加强要素保障,促进上下游、产供销、大中小企业协同复工达产。要加快推动各类商场、市场和生活服务业恢复到正常水平,畅通产业循环、市场循环、经济社会循环。要加强国际协调合作,共同维护国际产业链供应链安全稳定。'
wc('china_map(1).png',txt,'wordcloud.png')
# 调用
wc_ex()