如何使用Figure(matplotlib FigureCanvasQTAgg)绘制具有多个y轴的共享x轴子图?

Posted

技术标签:

【中文标题】如何使用Figure(matplotlib FigureCanvasQTAgg)绘制具有多个y轴的共享x轴子图?【英文标题】:How to draw share xaxis subplot with multiple yaxis with Figure(matplotlib FigureCanvasQTAgg)? 【发布时间】:2019-01-06 09:10:29 【问题描述】:

我想在垂直层中绘制一个共享xaxis 但不同yaxis 的图形,如下图所示。

我试过了

import sys
import matplotlib
matplotlib.use("Qt5Agg")
from PyQt5 import QtCore
from PyQt5.QtWidgets import QApplication, QMainWindow, QMenu, QVBoxLayout, QSizePolicy, QMessageBox, QWidget
from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.figure import Figure
from matplotlib.dates import num2date, date2num
import datetime

class GraphCanvas(FigureCanvas):
    def __init__(self, parent=None, width=1, height=1, dpi=100):
        fig = Figure(figsize=(width, height), dpi=dpi,facecolor='#041105') #figure options
        #first subplot
        self.axes = fig.add_subplot(211,facecolor='#041105')
        self.axes.tick_params(axis='both',color='#ffffff',labelcolor ='#ffffff') #tick options
        self.axes.grid(color='lightgray', linewidth=.5, linestyle=':')
        self.axes.yaxis.tick_right()  # show yaxis tick text in right side
        self.axes.xaxis_date()
        #second subplot
        self.axes2 = fig.add_subplot(212,facecolor='#041105')
        self.axes2.tick_params(axis='both', color='#ffffff', labelcolor='#ffffff')  # tick options
        self.axes2.grid(color='lightgray', linewidth=.5, linestyle=':')
        self.axes2.yaxis.tick_right()  # show yaxis tick text in right side
        self.axes2.xaxis_date()

        # ploting all trace
        self.plot_traces()
        FigureCanvas.__init__(self, fig)
        self.setParent(parent)
        FigureCanvas.setSizePolicy(self,
                QSizePolicy.Expanding,
                QSizePolicy.Expanding)
        FigureCanvas.updateGeometry(self)
class GraphTraces(GraphCanvas):
    """Simple canvas with a sine plot."""
    def plot_traces(self):
        dates = ['2017/01/01', '2017/01/02', '2017/01/03', '2017/01/04', '2017/01/05','2017/01/06','2017/01/07']
        x = date2num([datetime.datetime.strptime(d, '%Y/%m/%d').date() for d in dates])
        #scatter line chart
        y1 = [2,5,4,7,6,5,4]
        self.axes.plot(x, y1,color='orange')
        #bar chart
        y2 = [2,5,4,7,6,5,4]
        self.axes2.bar(x, y2,width=.8,color='g')

class ApplicationWindow(QMainWindow):
    def __init__(self):
        QMainWindow.__init__(self)
        self.setAttribute(QtCore.Qt.WA_DeleteOnClose)
        self.setWindowTitle("application main window")
        self.file_menu = QMenu('&File', self)
        self.file_menu.addAction('&Quit', self.fileQuit,
                QtCore.Qt.CTRL + QtCore.Qt.Key_Q)
        self.menuBar().addMenu(self.file_menu)
        self.help_menu = QMenu('&Help', self)
        self.menuBar().addSeparator()
        self.menuBar().addMenu(self.help_menu)

        self.help_menu.addAction('&About', self.about)
# plot widget
        self.plot_widget = QWidget(self)
        layout = QVBoxLayout(self.plot_widget)
        graph = GraphTraces(self.plot_widget, width=10, height=8, dpi=100)
        layout.addWidget(graph)
        self.plot_widget.setFocus()
        self.setCentralWidget(self.plot_widget)

        self.statusBar().showMessage("Status!", 2000)

    def fileQuit(self):
        self.close()
    def closeEvent(self, ce):
        self.fileQuit()
    def about(self):
        QMessageBox.about(self, "About",
  )

if __name__ == '__main__':
    app = QApplication(sys.argv)

    aw = ApplicationWindow()
    aw.setWindowTitle("Matplot in PyQt5 in main window")
    aw.show()
    app.exec_()

得到输出

[注意] 当我使用 twinx 时,子图相互重叠,而 pyplot sharexPyQt5 主窗口

上不起作用 FigureCanvas

我也尝试关注this 的答案,但无法在 PyQt5 主窗口中绘制此图。

【问题讨论】:

【参考方案1】:

您需要在子图之间共享 x 轴。

您可以使用sharex 参数这样做

ax1 = fig.add_subplot(211)
ax2 = fig.add_subplot(212, sharex=ax1)

或者,更方便的方法是使用subplots

ax1, ax2 = fig.subplots(nrows=2, sharex=True)

【讨论】:

太棒了!它对我有用。非常感谢@ImportanceOfBeingErnest

以上是关于如何使用Figure(matplotlib FigureCanvasQTAgg)绘制具有多个y轴的共享x轴子图?的主要内容,如果未能解决你的问题,请参考以下文章

如何更改 matplotlib 中轴对象刻度的字体大小 [重复]

如何使用python的matplotlib画正弦函数图像

matplotlib模块学习笔记

如何在 Matplotlib 中为子图添加标题

将matplotlib.rcParams字典正确重置为其原始默认值

如何向 Matplotlib 图例添加多个元素?