Python matplotlib 和 subplots 属性

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/38662667/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 21:16:33  来源:igfitidea点击:

matplotlib and subplots properties

pythonmatplotlib

提问by vandelay

I'm adding a matplotlib figure to a canvas so that I may integrate it with pyqt in my application. I were looking around and using plt.add_subplot(111)seem to be the way to go(?) But I cannot add any properties to the subplot as I may with an "ordinary" plot

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

figure setup

图形设置

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)

creating subplot and adding data

创建子图并添加数据

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)

I'd like to set x and y labels, but if I do ax.xlabel("Test")

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

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

which is possible if I did it by not using subplot

如果我不使用子图,这是可能的

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()

So I guess my question is, is it not possible to modify subplots further? Or is it possible for me to plot graphs in a pyqt canvas, without using subplots so that I may get benefit of more properties for my plots.

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

回答by Suever

plt.subplotreturns a subplot object which is a type of axes object. It has two methods for adding axis labels: set_xlabeland set_ylabel:

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

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

You could also call plt.xlabeland plt.ylabel(like you did before) and specify the axes to which you want the label applied.

您还可以调用plt.xlabeland plt.ylabel(就像您之前所做的那样)并指定要应用标签的轴。

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

Since you only have one axes, you could also omit the axeskwarg since the label will automatically be applied to the current axes if one isn't specified.

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

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