python - 在一行中设置 x 和 y 标签

标签 python matplotlib axis-labels

如果我想为每个轴设置 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/

相关文章:

python - 如何查看使用 `sudo pip install` 安装了哪些软件包?

python - 从 pandas df 更新数据库中的现有行

python - 带有圆圈表示人口规模的热图

python - 从数据帧创建一系列饼图,并将颜色链接到索引值

javascript - SI 刻度格式与小数刻度域

r - 更改轴标签的颜色

python - 如何使用输入调用测试函数?

python - 删除 matplotlib 中的工具栏按钮

python - matplotlib 第二轴标签未显示

python - Django 测试重定向以使用下一个参数登录