Hi,

Sure, here's a working example. Obviously a very simple plot layout, but 
you can fancy it up as required:

test_matplotlib.py
#!/usr/bin/env python3

import sys
from PyQt5 import QtCore, QtWidgets, uic
from PyQt5.QtWidgets import QFileDialog
import numpy as np
import pyqtgraph as pg
import test_matplotlib_plots as plots


class PlotWindow(QtWidgets.QMainWindow):

    def __init__(self):
        super().__init__()

        pg.setConfigOptions(antialias=True)

        # Load GUI layout from .ui file (named same as this source file, 
but with .ui extension)
        uic.loadUi(__file__.split('.py')[0] + '.ui', self)

        # Finish up the GUI and connections
        self.statusbar.showMessage("Welcome!")
        self.actionExport.triggered.connect(self.export_plot)
        self.plot = self.glw.addPlot()

        # Make some test data
        self.xcoords = np.arange(0, 100, 3)
        self.data = 50.0*np.random.random((5, self.xcoords.shape[0]))
        self.data += 1.0 + 2.0*self.xcoords

        # Plot test data
        self.errorbars = pg.ErrorBarItem(x=self.xcoords, y=np.mean(self.data
, axis=0), height=np.std(self.data, axis=0), beam=1)
        self.plot.addItem(self.errorbars)
        self.plot.plot(x=self.xcoords, y=np.mean(self.data, axis=0), symbol=
"o")
        self.plot.setLabels(bottom="Time, (s)", left="Intensity (a.u.)")

    def export_plot(self):
        self.statusbar.showMessage('Exporting plot...')
        filename, _ = QFileDialog.getSaveFileName(self, "Export As...", "", 
"PDF 
Image (*.pdf);;All Files (*)")
        if filename:
            # Remove any duplicated file extensions that Qt might add
            filename = filename.partition(".pdf")[0] + ".pdf"
            plots.testdata_image(self.xcoords, self.data, filename, label="Test 
data", xlim=self.plot.viewRange()[0], ylim=self.plot.viewRange()[1])
            self.statusbar.showMessage("Data saved to {}.".format(filename))
        else:
            self.statusbar.showMessage("Export cancelled.")

def main():
    app = QtWidgets.QApplication(sys.argv)
    mainwindow = PlotWindow()
    mainwindow.show()
    sys.exit(app.exec_())


if __name__ == '__main__':
    main()

test_matplotlib_plots.py
import numpy as np
import matplotlib.pyplot as plt
from cycler import cycler
from matplotlib.ticker import AutoMinorLocator


def testdata_figure(xcoords, data, **kwargs):
    """Plot data, returning a matplotlib figure object."""

    args = {"xlim": None,
            "ylim": None,
            "label": "",
            "xlabel": "Time (s)",
            "ylabel": "Intensity (a.u.)",
            "ccycle": ['#0000a0', '#a00000', '#00a000', '#000000', '#a000a0'
, '#a0a000', '#00a0a0', '#808080'],
            "figsize": (5.0, 3.75),
            "legendloc": "best"}
    args.update(kwargs)

    # Configure figure, axes
    fig, ax = plt.subplots(figsize=args["figsize"])
    ax.set_prop_cycle(cycler('color', args["ccycle"]))
    ax.set_xlabel(args["xlabel"])
    ax.set_ylabel(args["ylabel"])
    if args["xlim"] is not None:
        ax.set_xlim(args["xlim"])
    if args["ylim"] is not None:
        ax.set_ylim(args["ylim"])
    ax.xaxis.set_minor_locator(AutoMinorLocator(2))
    ax.yaxis.set_minor_locator(AutoMinorLocator(2))

    ax.errorbar(xcoords, np.mean(data, axis=0), yerr=np.std(data, axis=0), 
capsize=3, label=args["label"])

    ax.legend(fontsize='medium', frameon=False, loc=args["legendloc"])

    plt.tight_layout()
    return fig

def testdata_image(xcoords, data, output_filename, **kwargs):
    """Plot data to an image file."""

    args = {"dpi": 300}
    args.update(kwargs)
    fig = testdata_figure(xcoords, data, **kwargs)
    fig.savefig(output_filename, dpi=args["dpi"])
    plt.close(fig)

test_matplotlib.ui
<?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
 <class>MainWindow</class>
 <widget class="QMainWindow" name="MainWindow">
  <property name="geometry">
   <rect>
    <x>0</x>
    <y>0</y>
    <width>800</width>
    <height>600</height>
   </rect>
  </property>
  <property name="windowTitle">
   <string>Test MPL Export</string>
  </property>
  <widget class="QWidget" name="centralwidget">
   <layout class="QHBoxLayout" name="horizontalLayout">
    <item>
     <widget class="GraphicsLayoutWidget" name="glw"/>
    </item>
   </layout>
  </widget>
  <widget class="QMenuBar" name="menubar">
   <property name="geometry">
    <rect>
     <x>0</x>
     <y>0</y>
     <width>800</width>
     <height>19</height>
    </rect>
   </property>
   <widget class="QMenu" name="menuFile">
    <property name="title">
     <string>&amp;File</string>
    </property>
    <addaction name="actionExport"/>
    <addaction name="separator"/>
    <addaction name="actionExit"/>
   </widget>
   <addaction name="menuFile"/>
  </widget>
  <widget class="QStatusBar" name="statusbar"/>
  <action name="actionExport">
   <property name="text">
    <string>&amp;Export plot...</string>
   </property>
  </action>
  <action name="actionExit">
   <property name="text">
    <string>E&amp;xit</string>
   </property>
  </action>
 </widget>
 <customwidgets>
  <customwidget>
   <class>GraphicsLayoutWidget</class>
   <extends>QGraphicsView</extends>
   <header>pyqtgraph</header>
  </customwidget>
 </customwidgets>
 <resources/>
 <connections>
  <connection>
   <sender>actionExit</sender>
   <signal>triggered()</signal>
   <receiver>MainWindow</receiver>
   <slot>close()</slot>
   <hints>
    <hint type="sourcelabel">
     <x>-1</x>
     <y>-1</y>
    </hint>
    <hint type="destinationlabel">
     <x>399</x>
     <y>299</y>
    </hint>
   </hints>
  </connection>
 </connections>
</ui>

Patrick


On Friday, 18 January 2019 01:16:48 UTC+10:30, Trifon Trifonov wrote:
>
>
> Dear Patrick,
>
> Thank you for your answer! Can you please provide one very minimal example 
> how you did it!
> It will help me to accelerate a bit.
>
>
>
> Thanks!
> Trifon
>
>
> On Thursday, January 17, 2019 at 5:14:40 AM UTC+1, Patrick wrote:
>>
>> Hi,
>>
>> If you have a handle to the pyqtgraph ErrorBarItem, then you can extract 
>> the error bar lengths from the opts dictionary (
>> http://www.pyqtgraph.org/documentation/_modules/pyqtgraph/graphicsItems/ErrorBarItem.html#ErrorBarItem).
>>  
>> You might need to do a bit of code since opts["height"] is supposed to 
>> override opts["top"] and opts["bottom"] etc.
>>
>> This probably isn't helpful, but in my code base I have written a 
>> separate "plots.py" with various matplotlib routines to generate custom 
>> plot figures/files since it is simple enough, gives much more 
>> flexible/customisable plots, and bypasses limitations of pyqtgraph exports.
>>
>> Patrick
>>
>>
>>

-- 
You received this message because you are subscribed to the Google Groups 
"pyqtgraph" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to [email protected].
To view this discussion on the web visit 
https://groups.google.com/d/msgid/pyqtgraph/9529a49e-6a5a-43b4-93bc-7b7e95dc18be%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Reply via email to