【问题标题】:matplotlib and subplots propertiesmatplotlib 和子图属性
【发布时间】:2016-07-29 15:39:57
【问题描述】:

我正在向画布添加一个 matplotlib 图,以便我可以将它与我的应用程序中的 pyqt 集成。我环顾四周并使用plt.add_subplot(111) 似乎是要走的路(?)但我不能像使用“普通”情节一样向子情节添加任何属性

人物设置

self.figure1 = plt.figure()
self.canvas1 = FigureCanvas(self.figure1)
self.graphtoolbar1 = NavigationToolbar(self.canvas1, frameGraph1)

hboxlayout = qt.QVBoxLayout()

hboxlayout.addWidget(self.graphtoolbar1)
hboxlayout.addWidget(self.canvas1)

frameGraph1.setLayout(hboxlayout)

创建子图并添加数据

df = self.quandl.getData(startDate, endDate, company)

ax = self.figure1.add_subplot(111)
ax.hold(False)
ax.plot(df['Close'], 'b-')
ax.legend(loc=0)
ax.grid(True)

我想设置 x 和 y 标签,但如果我这样做ax.xlabel("Test")

AttributeError: 'AxesSubplot' object has no attribute 'ylabel'

如果我不使用子图来做到这一点,这是可能的

plt.figure(figsize=(7, 4))
plt.plot(df['Close'], 'k-')
plt.grid(True)
plt.legend(loc=0)
plt.xlabel('value')
plt.ylabel('frequency')
plt.title('Histogram')
locs, labels = plt.xticks()
plt.setp(labels, rotation=25)
plt.show()

所以我想我的问题是,不能进一步修改子图吗?或者我是否可以在 pyqt 画布中绘制图形,而不使用子图,以便我可以从我的图的更多属性中受益。

【问题讨论】:

    标签: python matplotlib


    【解决方案1】:

    plt.subplot 返回一个子图对象,它是一种轴对象。它有两种添加轴标签的方法:set_xlabelset_ylabel

    ax = plt.subplot('111')
    ax.set_xlabel('X Axis')
    ax.set_ylabel('Y Axis')
    

    您也可以调用 plt.xlabelplt.ylabel(就像您之前所做的那样)并指定您希望应用标签的轴。

    ax = plt.subplot('111')
    plt.xlabel('X Axis', axes=ax)
    plt.ylabel('Y Axis', axes=ax)
    

    由于您只有一个轴,因此您也可以省略 axes kwarg,因为如果未指定,标签将自动应用于当前轴。

    ax = plt.subplot('111')
    plt.xlabel('X Axis')
    plt.ylabel('Y Axis')
    

    【讨论】:

    • 成功了,谢谢!是否可以旋转 x 标签?
    • @vandelay 当然。您可以使用rotation kwarg:plt.xlabel('X Axis', rotation=30)
    • @vandelay 你想旋转绘图本身吗?你也可以只做label = ax.set_xlabel('X Axis') 然后label.set_rotation(30)
    • @vandelay 哦,那些是刻度标签。见here
    • 这对我有用。尽管如此,当从使用 pyplot (plt) 直接绘制到创建图形并使用它时,我发现更改方法的名称非常令人困惑。
    猜你喜欢
    • 1970-01-01
    • 2021-06-27
    • 1970-01-01
    • 1970-01-01
    • 2018-02-12
    • 2015-02-20
    • 2020-12-19
    • 1970-01-01
    • 2017-07-01
    相关资源
    最近更新 更多