Python: matplotlib drawing and common attribute settings

Introduce

This article is a summary of the quick reference table related to matplotlib.

The structure of a picture

Python is object-oriented, and the use of matplotlib to draw pictures is easier to understand from an object-oriented perspective.

  • Figure object
    can be seen as a canvas. After you have the canvas, you can draw various pictures on it.
  • The Axes object
    is the picture you want to draw. Then this diagram must contain a lot of information, such as curves, axes, titles, legends, notes, etc. These are the attributes contained in the Axes object, they are also various objects. For example Line2D, XAxis, YAxis

So the so-called drawing is to set various attributes of Axes. See the official documentation for all attributes of Axes.
More specific as shown below:

Common Line2D attributes

Examples of common attribute value
settings

    ax.plot(np.arange(6), color='b', linestyle='--', marker='+')
    ax.plot(np.arange(6), 'b--+')  #可通过符号标记快速设置,与上句等价

Common settings

ax.set_xlabel('x')	    #设置x轴名称
ax.set_ylabel('y')	    #设置y轴名称
ax.set_title('title')	#设置标题
ax.legend()	            #设置图例:
                            #方法1:ax.plot(x1,y1,label='label1',x2,y2,label='label1') ax.legend()
                            #方法2:ax.plot(x1,y1,,x2,y2) ax.legend(('label1', 'label2'))
                            #可设置图例位置属性:ax.legend(loc='best'),其他位置包括:'upper right','upper left',
                              'lower right','lower left','center'等
ax.set_xlim(0,5)       #设置x轴范围
ax.set_ylim(0,5)       #设置y轴范围
ax.set_xticks((0, 2, 4, 6))  #设置x轴刻度
ax.set_xticks((0, 2, 4, 6))  #设置y轴刻度
ax.set_xticklabels(labels=['x1','x2','x3','x4'],rotation=30,fontsize='small')  #设置x刻度的显示文本
ax.set_yticklabels()    #设置y刻度的显示文本,同上
ax.text()               #指定位置显示文本
ax.annotate()           #添加标注,参数:注释文本、指向点、文字位置、箭头属性
ax.grid()               #显示网格

reference

Published 47 original articles · Like 33 · Visit 310,000+

Guess you like

Origin blog.csdn.net/kaever/article/details/105317720