面向对象绘图
# Matplotlib中图像的结构
atplotlib图像中最重要的三个对象分别是figure
(画布),ax
(坐标系),axis
(坐标轴)。一个figure
中可以有多个 ax(多个子图),figure可以设置图像的尺寸,背景色,像素等。一个ax
中一般有多个 axis,如xaxis
,yaxis
。ax
可以设置子图的大小,标题,数据的呈现形式,线型,颜色等。axis
又有label
,tick
等对象,可以设置坐标轴刻度,坐标轴标签,坐标轴标题等。
面向对象绘图一般自上而下: 0,绘图前设置绘图风格等全局参数,例如style,font等。
1,开始绘图时,首先是figure对象布局,包括大小size,像素dpi等。
2, 接着是axes对象规划,包括图形(如点线柱饼),axes区域(如背景颜色,栅格,图例)等。
3,然后是axis对象设置,包括坐标轴,刻度线,标签等。
4,最后是添加文字信息,包括标题,数据标注,其他文字说明等。
绘图前设置绘图风格等全局参数
例如style,font等。
# 查看可用的绘图风格
print(plt.style.available)
# 选择绘图风格
plt.style.use('bmh')
# 用来正常显示中文标签
plt.rcParams['font.sans-serif'] = ['FangSong'] # 指定默认字体
# 解决符号‘-’显示为方块的问题
plt.rcParams['axes.unicode_minus'] = False
# 设置全局默认字体属性
font = {'weight': 'bold', 'size': 15}
plt.rc('font', **font)
1,开始绘图时,首先是figure对象布局,包括大小figsize,像素dpi等。
fig = plt.figure()
2,接着是axes对象规划,包括图形(如点线柱饼),axes区域(如背景颜色,栅格,图例)等。
ax = fig.add_subplot(111, facecolor=(0, 1, 0, 0.3))
# ax.figure(dpi=600)
ax.plot(x, y,
label='$sin(x)$',
color='r',
linestyle="-",
linewidth=3,
marker="o", markeredgecolor='g', markersize=8,
markerfacecolor='red',
alpha=0.8)
# 网格设置
ax.grid(color='b', linestyle=':', linewidth=1)
# 图例设置
ax.legend(loc='best', fontsize=18, frameon=True)
plt.show()
3,然后是axis对象设置,包括坐标轴,刻度线,标签等。
# 坐标轴的范围
ax.axis([-0.5, 6.5, -1.1, 1.1])
# 设置刻度
ax.xaxis.set_ticks([0, np.pi / 2, np.pi, 3 * np.pi / 2, 2 * np.pi])
# 设置刻度标签
ax.xaxis.set_ticklabels(['$0$', '$\\frac{\pi}{2}$',
'$\pi$', '$\\frac{3\pi}{2}$',
'$2\,\pi$'
])
# ax.set_xticks()
# ax.set_xticklabels()
# ax.xaxis.set_major_locator()
# ax.xaxis.set_major_formatter()
# 设置坐标轴标题
ax.set_xlabel('X ', fontsize=20)
ax.set_ylabel('Y ', fontsize=20, rotation=0)
# ax.xaxis.set_label_text('X',fontsize = 20)
# ax.yaxis.set_label_text('y',fontsize = 20,rotation =0)
# 设置坐标轴。标签的位置
ax.xaxis.set_label_coords(1,-0.05)
ax.yaxis.set_label_coords(-0.05,1)
# 设置坐标轴是否可见
ax.spines['right'].set_visible(False)
#设置坐标轴颜色,当颜色为 none 时,坐标轴不可见
ax.spines['top'].set_color('none')
ax.spines['bottom'].set_color('red')
# 移动坐标轴的位置
ax.spines['left'].set_position(("data",0))
ax.spines['bottom'].set_position(("data",0))
4,最后是添加文字信息,包括标题,数据标注,其他文字说明等。
# 设置标题
ax.set_title(u'正弦曲线',color='black',fontsize=20)
# ax.annotate(-3.7, 3, r'$This\ is\ the\ some\ text. \mu\ \sigma_i\ \alpha_t$',
# )
# ax.text(0.85,0.75,'matplotlib\n plot',fontsize=20,
# horizontalalignment='center',
# verticalalignment='center',
# transform= ax.transAxes,
# bbox=dict(facecolor='green',alpha=0.6))
fig.savefig(u'02020202.png',dpi=600)
其它方法;
formatter = ticker.FormatStrFormatter('$%1.2f')
ax.yaxis.set_major_formatter(formatter)
case 1
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.ticker as ticker
# Fixing random state for reproducibility
np.random.seed(19680801)
fig, ax = plt.subplots()
ax.plot(100*np.random.rand(20))
formatter = ticker.FormatStrFormatter('$%1.2f')
ax.yaxis.set_major_formatter(formatter)
for tick in ax.yaxis.get_major_ticks():
tick.label1.set_visible(False)
tick.label2.set_visible(True)
tick.label2.set_color('green')
# ax.yaxis.get_major_ticks() 返回两个纵轴的坐标,label1,label2分别表示不同的轴
plt.show()
Formatters and Locators
'Axis.get_major_formatter' Get the formatter of the major ticker
'Axis.get_major_locator' Get the locator of the major ticker
'Axis.get_minor_formatter' Get the formatter of the minor ticker
'Axis.get_minor_locator ' Get the locator of the minor ticker
'Axis.set_major_formatter' Set the formatter of the major ticker.
'Axis.set_major_locator ' Set the locator of the major ticker.
'Axis.set_minor_formatter' Set the formatter of the minor ticker.
'Axis.set_minor_locator' Set the locator of the minor ticker.
from matplotlib.ticker import NullFormatter, FixedLocator
ax.grid(True)
ax.set_xlim([-180, 180])
ax.yaxis.set_minor_formatter(NullFormatter())
ax.yaxis.set_major_locator(FixedLocator(np.arange(-90, 90, 30)))
ax.xaxis.set_major_locator(MultipleLocator(20)) # 设置20倍数
ax.xaxis.set_major_formatter(FormatStrFormatter('%5.1f')) # 设置文本格式
# y轴
ax.yaxis.set_major_locator(MultipleLocator(100)) # 设置100倍数
ax.yaxis.set_major_formatter(FormatStrFormatter('%1.2f')) # 设置文本格式
# 设置轴的副刻度
# x轴
ax.xaxis.set_minor_locator(MultipleLocator(5)) # 设置10倍数
# ax.xaxis.set_minor_formatter(FormatStrFormatter('%2.1f')) # 设置文本格式
# y轴
ax.yaxis.set_minor_locator(MultipleLocator(50)) # 设置50倍数
# ax.yaxis.set_minor_formatter(FormatStrFormatter('%1.0f')) # 设置文本格式
Axis Label
'Axis.set_label_coords' Set the coordinates of the label.
'Axis.set_label_position' Set the label position (top or bottom)
'Axis.set_label_text' Set the text value of the axis label.
'Axis.get_label_position' Return the label position (top or bottom)
'Axis.get_label_text' Get the text of the label
Ticks, tick labels and Offset text
'Axis.grid' Configure the grid lines.
'Axis.set_tick_params' Set appearance parameters for ticks, ticklabels, and gridlines.
'Axis.axis_date' Sets up axis ticks and labels treating data along this axis as dates.
axis.Axis.set_tick_params
Set appearance parameters for ticks, ticklabels, and gridlines.
参数:Matplotlib:tick_params matplotlib.axes.Axes.tick_params
axes.Axes.set_title
Axes.set_title(self, label,
fontdict=None,
loc=None, pad=None,
*, y=None, **kwargs)
参数:
label
: str Text to use for the titlefontdict
:dict A dictionary controlling the appearance of the title text, the default fontdict is:{'fontsize': rcParams['axes.titlesize'], 'fontweight': rcParams['axes.titleweight'], 'color': rcParams['axes.titlecolor'], 'verticalalignment': 'baseline', 'horizontalalignment': loc}
loc
: {'center', 'left', 'right'}, default:rcParams["axes.titlelocation"]
(default:'center'
)which title to set.y
: float, default:rcParams["axes.titley"]
(default:None
)Vertical axes loation for the title (1.0 is the top). If None (the default), y is determined automatically to avoid decorators on the axes.
pad
:float, default:rcParams["axes.titlepad"]
(default:6.0
)The offset of the title from the top of the axes, in points.
返回值:
-
The matplotlib text instance representing the title
Discouraged
'Axis.set_ticklabels' Set the text values of the tick labels.
'Axis.set_ticks' Set the locations of the tick marks from sequence ticks
双Y轴
ax2 = ax1.twinx() # instantiate a second axes that shares the same x-axis
ax2.tick_params(axis='y', labelcolor=color)
# 刻度和标签设置
matplotlib.axes.Axes.tick_params
设置刻度线和刻度标签的位置 matplotlib.axis.YAxis.set_ticks_position
axis.Axis.set_ticks()
设置刻度和标签
Axis.set_ticks(self, ticks, minor=False)
ticks : sequence of floats
minor : bool
设置刻度和标签
Axis.set_ticks_position(self, position)
设置刻度和标签的位置
YAxis.set_ticks_position(self, position)
Parameters:
position : {'left', 'right', 'both', 'default', 'none'}
如果时y轴的,可以设置参数为上面的
# loc 表示位置,spine表示当前位置的对象
for loc, spine in ax.spines.items():
print(loc)
print(spine)
left
Spine
right
Spine
bottom
Spine
top
Spine
spines.Spine.set_position()
设置 X,Y,轴分离开:
1.spines.Spine.set_position
.set_position(self, position)
spine.set_position(('outward', 10)) # outward by 10 points
2. .set_color(self, c)
3. .set_smart_bounds(self, value)
Spine Placement Demo:
fig = plt.figure()
x = np.linspace(-np.pi, np.pi, 100)
y = 2 * np.sin(x)
ax = fig.add_subplot(2, 2, 1)
ax.set_title('centered spines')
ax.plot(x, y)
ax.spines['left'].set_position('center')
ax.spines['right'].set_color('none')
ax.spines['bottom'].set_position('center')
ax.spines['top'].set_color('none')
ax.spines['left'].set_smart_bounds(True)
ax.spines['bottom'].set_smart_bounds(True)
ax.xaxis.set_ticks_position('bottom')
ax.yaxis.set_ticks_position('left')
ax = fig.add_subplot(2, 2, 2)
ax.set_title('zeroed spines')
ax.plot(x, y)
ax.spines['left'].set_position('zero')
ax.spines['right'].set_color('none')
ax.spines['bottom'].set_position('zero')
ax.spines['top'].set_color('none')
ax.spines['left'].set_smart_bounds(True)
ax.spines['bottom'].set_smart_bounds(True)
ax.xaxis.set_ticks_position('bottom')
ax.yaxis.set_ticks_position('left')
ax = fig.add_subplot(2, 2, 3)
ax.set_title('spines at axes (0.6, 0.1)')
ax.plot(x, y)
ax.spines['left'].set_position(('axes', 0.6))
ax.spines['right'].set_color('none')
ax.spines['bottom'].set_position(('axes', 0.1))
ax.spines['top'].set_color('none')
ax.spines['left'].set_smart_bounds(True)
ax.spines['bottom'].set_smart_bounds(True)
ax.xaxis.set_ticks_position('bottom')
ax.yaxis.set_ticks_position('left')
ax = fig.add_subplot(2, 2, 4)
ax.set_title('spines at data (1, 2)')
ax.plot(x, y)
ax.spines['left'].set_position(('data', 1))
ax.spines['right'].set_color('none')
ax.spines['bottom'].set_position(('data', 2))
ax.spines['top'].set_color('none')
ax.spines['left'].set_smart_bounds(True)
ax.spines['bottom'].set_smart_bounds(True)
ax.xaxis.set_ticks_position('bottom')
ax.yaxis.set_ticks_position('left')
```python import matplotlib.pyplot as plt import numpy as np
def adjust_spines(ax,spines): for loc, spine in ax.spines.items(): if loc in spines: spine.set_position(('outward', 10)) # outward by 10 points else: spine.set_color('none') # don't draw spine
# turn off ticks where there is no spine
if 'left' in spines:
ax.yaxis.set_ticks_position('left')
else:
# no yaxis ticks
ax.yaxis.set_ticks([])
if 'bottom' in spines:
ax.xaxis.set_ticks_position('bottom')
else:
# no xaxis ticks
ax.xaxis.set_ticks([])
fig = plt.figure()
x = np.linspace(0,2np.pi,100) y = 2np.sin(x)
ax = fig.add_subplot(2,2,1) ax.plot(x,y) adjust_spines(ax,['left'])
ax = fig.add_subplot(2,2,2) ax.plot(x,y) adjust_spines(ax,[])
ax = fig.add_subplot(2,2,3) ax.plot(x,y) adjust_spines(ax,['left','bottom'])
ax = fig.add_subplot(2,2,4) ax.plot(x,y) adjust_spines(ax,['bottom'])
plt.show()
```
...... 更多参考官方文档:https://matplotlib.org/api/axis_api.html