全球各大洲師生比例數據如下(部分):所需文章為student_ratio_count 。
world_avg = 23.518193030303order=["Africa", "Oceania","Asia","South America","North America","Europe"]palette=["#0076BB", "#152769","#1AB6AF", "#E9E4A6","#FF3100","#E9A17C"]region_color = dict(zip(order,palette))region_colorregion_y = {'Africa':1,'Oceania':2,'Asia':3,'South America':4,'North America':5,'Europe':6}sactter_line = student[['student_ratio_cont','region']].drop_duplicates()sactter_line["region_y"] = [region_y[i]-1 for i in sactter_line['region']]sactter_linelegend_data = student[['x','y','region']]legend_data.head()本文的可視化繪製過程涉及seaborn的stripplot()方法,所需的庫、總體設置及用於繪製「抖動」的散點圖(類似ggplot2的position_jitter()),其目的就是為了防止散點重疊。如下:import seaborn as snsimport matplotlib.lines as mlinesfrom mpl_toolkits.axes_grid1.inset_locator import inset_axesfrom matplotlib.patches import Rectangle
plt.rcParams['font.family'] = ['Roboto Mono']fig, ax = plt.subplots(figsize=(10,6),dpi = 200,facecolor='#323332',edgecolor='#323332')ax.set_facecolor("#323332")sns.stripplot(x="student_ratio", y="region",order=order,palette=palette, data=student, size = 8,alpha=.4,edgecolor = "white",linewidth=.8,zorder=0,ax=ax)# #添加 點線 圖層def newline(p1, p2): ax = plt.gca() l = mlines.Line2D([p1[0],p2[0]], [p1[1],p2[1]],color='#FFFFFF', lw=1.8,zorder = 0) ax.add_line(l)return lfor p1, p2 in zip(sactter_line['student_ratio_cont'], sactter_line['region_y']): newline([world_avg,p2], [p1,p2])#添加散點for i,j,c in zip(sactter_line['student_ratio_cont'], sactter_line['region_y'],sactter_line['region']): ax.scatter(i,j,c=region_color[c],s = 170,ec = 'white',lw=.8,zorder=1)
ax.tick_params(labelsize = 15,direction = 'out',colors = '#FFFFFF')ax.set_xticks(np.arange(-5,100,10))#設置軸脊顏色及寬度for spine in ['top','bottom','left','right']: ax.spines[spine].set_color("#FFFFFF") ax.spines[spine].set_linewidth(1.5)#隱藏xy軸的labelax.set_xlabel('')ax.set_ylabel('')ax.invert_yaxis()#添加另類圖例axins = inset_axes(ax, width=2.3, height=1.5)for x,y,c in zip(legend_data.x,legend_data.y,legend_data.region): rect = Rectangle((x+1,y+1),width=.5,height=.5, color=region_color[c]) axins.add_patch(rect)axins.set_xticks([])axins.set_xlim(left=-5,right=35)axins.set_yticks([])axins.set_ylim(top=30,bottom=-5)axins.invert_yaxis()axins.axis('off')這一步用到了matplotlib的axes插入方法,繪製大小圖或者中國地圖十段線部分均可用此方法進行繪製。這裡也用到了之前構造的lengend_data、region_color,然後使用 Rectangle()繪製矩形,再使用 axins.add_patch(rect)方法進行多矩形繪製。ggplot2的geom_tile()也可實現矩形圖表的繪製。ax.annotate(s="Worldwide average:\n{} students per teacher".format(round(world_avg,1)), xy=(world_avg,4.5),xytext=(40,5),ha="center",va="center",size=12,c='#FFFFFF', family='Poppins', arrowprops=dict(arrowstyle="->", connectionstyle="arc3,rad=-0.3",fc="gray",ec='#FFFFFF') )如果沒用採用地圖圖例的繪製,而是一般的散點圖圖例,效果如下:#添加圖例region_legend = ax.legend(fontsize=10,markerscale =1.2,title = 'Region',frameon=False, title_fontsize = 15)#region_legend.get_title().set_fontsize(fontsize = 13)#面向對象region_legend.get_title().set_color("#FFFFFF")region_legend.get_frame().set_facecolor('#323332')#修改圖例屬性顏色:圖例文字顏色設置for text in region_legend.get_texts(): text.set_color('#FFFFFF')Matplotlib對繪製大多數圖表還是比較友好的,也是比較容易定製化自己的繪圖需求(需熟悉太多的繪圖函數),但涉及統計圖表的繪製,可以結合seaborn進行繪製,使繪圖事半功倍哦!!繪圖的顏色搭配對繪圖結果至關重要,自己現階段也是在摸索和模仿,有好的顏色搭配學習網站或者資源,可以進群交流。本文能力有限,有錯誤的地方或者不理解的地方,可以後臺諮詢或者進行討論,期待你的加入。如需聯繫EasyShu團隊
請加微信:EasyCharts
微信公眾號【EasyShu】博文代碼集合地址
https://github.com/Easy-Shu/EasyShu-WeChat
《Python數據可視化之美》-配套原始碼下載地址
https://github.com/Easy-Shu/Beautiful-Visualization-with-python
《R語言數據可視化之美》-增強版配套原始碼下載地址
https://github.com/Easy-Shu/Beautiful-Visualization-with-R