Summary of python drawing skills

matplotlib font query and setting

* Requirements: I want Chinese fonts, but the font libraries of different systems are different. You need to find out which fonts are available and pick out what you want

Query all fonts in the current system and view

from matplotlib.font_manager import FontManager
import matplotlib.pyplot as plt
import matplotlib as mpl
import subprocess
mpl_fonts = set(f.name for f in FontManager().ttflist)
print('all font list get from matplotlib.font_manager:')
for f in sorted(mpl_fonts):
	mpl.rcParams['font.family'] = f # 字体设置方法,应用全局
    plt.plot([1,2],[1,2]) # 打印效果,这样就能找到中文字体了
    plt.xlabel('中文字体')
    print('\t' + f)

Matplotlib axis scale is displayed as a percentage

Just add these three lines before plt.show()

from matplotlib.ticker import FuncFormatter
def to_percent(temp, position):
      return '%1.2f'%(100*temp) + '%' # 这是显示格式,可根据需要调整
plt.gca().yaxis.set_major_formatter(FuncFormatter(to_percent))

ref:https://www.qb5200.com/article/389707.html

Image style related settings

  1. Picture length and width settings: plt.figure(figsiz=(10,5)), where 10 is the width (horizontal), 5 is the height (vertical);
  2. X-axis scale value change: plt.xticks(ticks=x_val, labels = tag_val), Requirement background: When the x-axis scale is a category variable, it is necessary to change the number to a character, where x_val indicates the original numerical scale, and tag_val is the replaced character, both of which are List;
  3. X-axis scale rotation: plt.xticks(rotation = 30), demand background: when the scale value is too large, horizontal placement will cause the scale to overlap, so the scale value needs to be rotated, and 30 is the rotation angle;
  4. Grid line setting:
    - Keep only the horizontal grid lines or only the vertical grid lines: plt.grid(aixs='y)or plt.grid(axis='x')
    - Place the grid lines at the bottom to avoid covering the target graphics: plt.grid(zorder=0), note that here also needs to be in the target drawing function (eg: plot , bar, hist) to add parameterszorder=100

save Picture

  1. Basic operation: fig.savefig('file_name')orplt.savefig('file_name')
  2. Set a transparent background:plt.savefig('file_name',transparent=True)
  3. Set the border size to be the same:plt.savefig('file_name',bbox_inches = 'tight')
  4. Set the inner and outer colors of the canvas:plt.savefig('file_name',facecolor = 'violet',edgecolor = 'lightgreen')
  5. Set image resolution:ply.savefig('file_name', dpi=600)

drawing template

Histogram + line chart + label settings
def bar_line(x_list,y_list,color_list,label_list,tag_list,tit,width=0.2,if_save=False):
    mpl.rcParams['font.family'] = 'WenQuanYi Micro Hei'
    plt.figure(figsize=(10,5))
    for i in range(len(y_list)): # bar + plot
        plt.bar([x+(i-1)*width for x in x_list], y_list[i], width,color = color_list[i],label = label_list[i],zorder = 100)
        plt.plot(x_list, y_list[i],'--',color = color_list[i],label = label_list[i], zorder = 100,linewidth=2.5)
    for i in range(len(x_list)): # text
        for j in range(len(y_list)):
            plt.text(x_list[i]+(j-1)*width, y_list[j][i] + 1, y_list[j][i], ha='center', fontsize=12)

    plt.title(tit,fontsize = 18)
    # x轴刻度标签位置不进行计算
    plt.xticks(ticks = np.arange(1,len(tag_list)+1),labels = tag_list,fontsize = 15)
    plt.yticks(fontsize = 15)
    plt.legend(fontsize = 15)
    plt.grid(axis = 'y',zorder=0)
    if if_save:
        plt.savefig(tit+'.png',bbox_inches = 'tight',dpi=600)
    plt.show()
stacked column chart

Note that the data here y_list[i]must be of numpy.ndarraytype, otherwise it cannot be accumulated

########### 堆叠柱状图
def stacked_bar(x_list,y_list,color_list,label_list,tag_list,tit,y_label,width=0.2,if_save=False):
    mpl.rcParams['font.family'] = 'WenQuanYi Micro Hei'
    plt.figure(figsize=(20,5))
    bottom = np.array([0]*len(tag_list))
    for i in range(len(y_list)):
        plt.bar(x_list, y_list[i], width,color = color_list[i],label = label_list[i],zorder = 100,bottom=bottom)
        bottom += y_list[i]
    plt.title(tit,fontsize = 20)
    plt.ylabel(y_label,fontsize = 18)
    # x轴刻度标签位置不进行计算
    plt.xticks(ticks = np.arange(1,len(tag_list)+1),labels = tag_list,fontsize = 15,rotation=30)
    plt.yticks(fontsize = 15)
    plt.legend(fontsize = 15)
    plt.grid(axis = 'y',zorder=0)
    if if_save:
        plt.savefig(tit+'.png',bbox_inches = 'tight',dpi=600)
    plt.show()

Guess you like

Origin blog.csdn.net/zyl_wjl_1413/article/details/125572125