【问题标题】:How to draw a frame on a matplotlib figure如何在 matplotlib 图形上绘制框架
【发布时间】:2018-01-17 00:27:21
【问题描述】:

我想在这个图中显示框架。 我尝试运行下面的代码,但它没有工作:

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)

【问题讨论】:

  • 看起来你不是在一个孤立的 matplotlib 图内绘图,而是在某个 GUI 的画布内绘图。我们需要更多信息。 tight_layout 是一种在图形框架内拉伸轴的图形方法,它与边框无关。
  • 我添加了画布的代码,希望它更清晰。
  • 你需要画布做什么?为什么不只使用 plt.plot(...) 绘制它
  • 我正在使用 Qt 作为 GUI,我需要一个画布来绘制图形。

标签: python pandas matplotlib time-series


【解决方案1】:

边框(或刺)已经可见,但是是白色的。您需要按照此回复中的说明更改颜色:https://stackoverflow.com/a/43265998/1773344

某种灰色的例子:

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://stackoverflow.com/a/22608025/1773344

【讨论】:

    【解决方案2】:

    重点是您似乎使用的是 seaborn 或至少是 seaborn darkgrid 样式。如果确实需要这样做,但您仍希望轴周围有边框,则需要更改样式。

    plt.rcParams["axes.edgecolor"] = "black"
    plt.rcParams["axes.linewidth"] = 1
    

    这(正如@Wli 提到的)在this answer 中进行了解释。

    这完全独立于tight_layoutplt.tight_layout() 产生所示错误的原因无法通过手头的信息确定。但是,通常调用图形的方法可能比在 GUI 中使用 pyplot 更好。所以你可以试试self.canvas.figure.tight_layout()

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-09-22
      • 2020-02-28
      • 2017-05-19
      • 2022-08-06
      • 2015-11-18
      • 2021-08-11
      • 1970-01-01
      • 2019-05-03
      相关资源
      最近更新 更多