如何在Matplotlib图表上绘制一个框架

8

我想在这张图片中展示一个框架。 enter image description here 我尝试运行下面的代码,但它没有起作用:

ax = self.canvas.figure.add_subplot(111)
ax.spines['top'].set_visible(True)
ax.spines['right'].set_visible(True)
ax.spines['bottom'].set_visible(True)
ax.spines['left'].set_visible(True)
ax.plot(diff)

我也尝试过:
plt.tight_layout()

但是会生成以下错误:

> File "runme.py", line 54, in autocorr_function
>     plt.tight_layout()   File "/usr/local/lib/python2.7/dist-packages/matplotlib/pyplot.py", line
> 1406, in tight_layout
>     fig.tight_layout(pad=pad, h_pad=h_pad, w_pad=w_pad, rect=rect)   File "/usr/local/lib/python2.7/dist-packages/matplotlib/figure.py",
> line 1753, in tight_layout
>     rect=rect)   File "/usr/local/lib/python2.7/dist-packages/matplotlib/tight_layout.py",
> line 326, in get_tight_layout_figure
>     max_nrows = max(nrows_list) ValueError: max() arg is an empty sequence

感谢您的帮助,谢谢。
编辑:这是画布的代码:
from matplotlib.backends.backend_qt4agg import FigureCanvasQTAgg as FigureCanvas 

import matplotlib.pyplot as plt from PyQt4 import QtGui 

class   Canvas(FigureCanvas):

     def __init__(self, parent=None):
         self.figure = plt.figure()     #plt.tight_layout(pad=4)
         FigureCanvas.__init__(self, self.figure)
         self.setParent(parent)
         FigureCanvas.setSizePolicy(self,
                                QtGui.QSizePolicy.Expanding,
                                QtGui.QSizePolicy.Expanding)
         FigureCanvas.updateGeometry(self)

1
看起来你并不是在一个孤立的 matplotlib 图像中绘图,而是在某个 GUI 的画布上绘图。我们需要更多信息。tight_layout 是一种图形方法,可以在图形框架内拉伸轴,与边框无关。 - hyamanieu
我添加了画布的代码,希望它能提供更多的清晰度。 - Sara Lussi
你需要画布来做什么?为什么不直接使用plt.plot(...)绘制它呢? - 2Obe
我正在使用Qt编写GUI,我需要一个画布来绘制图形。 - Sara Lussi
2个回答

7
边框(或脊梁)已经可见,但是是白色的。您需要按照此响应中的说明更改颜色:https://dev59.com/2lgQ5IYBdhLWcg3wIQVB#43265998 例如,可以使用某种灰色:
ax.spines['bottom'].set_color('0.5')
ax.spines['top'].set_color('0.5')
ax.spines['right'].set_color('0.5')
ax.spines['left'].set_color('0.5')

如果您想要轴周围的边框,没有简单的解决方案,除非将轴放在具有调整边框的轴内,如此答案中部分解释的那样:https://dev59.com/D2Eh5IYBdhLWcg3wRRqh#22608025


5
主要问题是您似乎正在使用seaborn或至少是seaborn darkgrid风格。如果确实如此,但您仍然想在轴周围有边框,则需要更改样式。
plt.rcParams["axes.edgecolor"] = "black"
plt.rcParams["axes.linewidth"] = 1

正如@Wli所提到的那样,这在这个答案中有解释。

这与tight_layout无关。不能确定为什么plt.tight_layout()会产生显示的错误,因为没有足够的信息。然而,在GUI中,您可能更好地调用图形的方法,而不是使用pyplot。因此,您可以尝试使用self.canvas.figure.tight_layout()


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接