如果我想为每个轴设置 x、y 标签,我必须这样做:
import matplotlib.pyplot as plt
plt.plot([1,2,3,4])
plt.ylabel('This is y label')
plt.xlabel('This is x label')
plt.show()
我需要分别设置xlabel
, ylabel
我想知道是否有任何语法可以让我做类似的事情:
plt.label('x label', 'y label')
所以代码看起来更紧凑?
或者我如何制作任何自定义函数来执行此操作?
最佳答案
一旦您开始更频繁地使用 matplotlib 的面向对象模型,您将能够将轴的所有相关参数作为关键字添加到创建这些轴的函数中。
一个简单的例子:
fig = plt.figure()
ax = fig.add_subplot(111, xlabel="time", ylabel="money")
一个更长的例子:
fig1 = plt.figure(figsize=(10,8))
ax1 = fig1.add_axes((0.1, 0.1, 0.8, 0.8), # full positional control
frameon=True, # display frame boundary
aspect='equal', # set aspect ratio upon creation
adjustable='box', # what part of the axes can change to meet the aspect ratio requirement?
xticks=[0.1, 1.2, 10],
xlabel='voltage (V)',
xlim=(0.05, 10.05),
yticks=[0, 10],
ylabel='current (µA)',
ylim=(0, 2))
根据收到的评论,您还可以使用“property batch setter”ax.set
,这是一个不错的 matplotlib 小便利函数。
plt.close('all')
plt.plot([1,2,3], [4, 7, 1])
plt.gca().set(xlabel='x', ylabel='y')
关于python - 在一行中设置 x 和 y 标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37538236/