[英]Passing optional arguments to, e.g., ax.set(ylabel=…)
阅读此问答后,我知道如何使用pyplot
命名空间将可选 arguments 指定为y label object
plt.ylabel('y', rotation='horizontal', ha='right')
或面向 object 的一个
ax.set_ylabel(...)
但我不知道我怎么可能使用方便的语法
ax.set(ylabel=???)
并且仍然可以指定其他参数。
一个简单的用法示例:
import matplotlib
import matplotlib.pyplot as plt
import numpy as np
# Data for plotting
t = np.arange(0.0, 2.0, 0.01)
s = 1 + np.sin(2 * np.pi * t)
fig, ax = plt.subplots()
ax.plot(t, s)
ax.set(xlabel='time (s)', ylabel='voltage (mV)',
title='About as simple as it gets, folks')
ax.grid()
fig.savefig("test.png")
plt.show()
请注意,您提到的其他两种方法可用的选项在使用ax.set()
时将不可用,因为这只是“属性批处理设置器” ,因此只会公开Axes
的属性。
The Axes
class doesn't have an override for the set()
method, so matplotlib.axes.Axes.set()
is the same as matplotlib.artist.Artist.set()
which calls matplotlib.artist.Artist.update()
使用指定的关键字参数列表( props
)。 update()
看起来像这样:
def update(self, props):
ret = []
with cbook._setattr_cm(self, eventson=False):
for k, v in props.items():
# ...
if k == "axes":
ret.append(setattr(self, k, v))
else:
func = getattr(self, f"set_{k}", None)
if not callable(func):
raise AttributeError(f"{type(self).__name__!r} object "
f"has no property {k!r}")
ret.append(func(v))
# ....
return ret
这将通过props
dict 并检查每个键是否存在self
的 setter 方法(在matplotlib.axes.Axes.set()
Axes
实例的情况下)是否存在,如果存在,则使用关联的值调用它,如果不是它引发AttributeError
。 这意味着您不能使用set()
方法来更改没有定义 setter 方法的属性(一个例外是您可以传递axes
参数来重置轴)。
由于matplotlib.axes.Axes
没有用于 label 旋转和对齐的设置器,因此您不能使用ax.set()
来改变这些。 您可以做的是在文本实例上调用.set()
,即
import matplotlib.pyplot as plt
fig, ax = plt.subplots(1)
ylab = ax.set_ylabel("y-label")
ylab.set(rotation="horizontal", ha="right")
我认为这是.set()
可能最接近您所需的用法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.