簡體   English   中英

將可選的 arguments 傳遞給例如 ax.set(ylabel=...)

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM