Как вставить matplotlib в pyqt

Вставить график matplotlib в графический интерфейс pyqt5

Я работаю с PyQt5, пытаясь сгенерировать графический интерфейс для моего инструмента анализа данных. Моя проблема в том, что я не понимаю, как встроить сюжет matplotlib с полной функциональностью.

Все учебники о PyQt5 и о том, как встраивать matplotlib, показывают очень простой способ, где они создают весь графический объект непосредственно в коде. Я не хочу этого делать, потому что мой графический интерфейс был сгенерирован с помощью Qt Designer. Я создал QWidget для отображения данных в нем. Поэтому я импортирую файл UI в коде:

Это файл test.ui, созданный Qt Designer:

Случилось так, что я могу видеть панель инструментов в моем окне, но теперь данные. Я могу использовать значок «Сохранить», чтобы сохранить график в виде изображения. Я думаю, что я создаю второй экземпляр объекта виджета, который не коррелирует с тем, который я создал в Qt Designer.

Как я могу решить эту проблему? Заранее спасибо!

2 ответа

Я думаю, вы сбиваете с толку, что вы создали виджет с именем plotWidge в Qt Designer, и вы делаете self.plotWidget = FigureCanvas(fig) его замену (даже если имена совпадают, что действие не выполнено), так что оно делает не вызывает путаницы, измените plotWidge на content_plot в Qt Designer, поэтому plotWidget должен быть помещен в content_plot с помощью макета.

Как вставить matplotlib в pyqt

Для тех, кто ищет решение, которое начинается с Qt Designer и заканчивается чем-то вроде этого кода этого учебного пособия:

Источник

Plotting with Matplotlib
Create PyQt5 plots with the popular Python plotting library

Graphics and Plotting course

This tutorial is also available for PySide2

In a previous tutorial we covered plotting in PyQt5 using PyQtGraph. PyQtGraph uses the Qt vector-based QGraphicsScene to draw plots and provides a great interface for interactive and high performance plotting.

However, there is another plotting library for Python which is used far more widely, and which offers a richer assortment of plots — Matplotlib. If you’re migrating an existing data analysis tool to a Python GUI, or if you simply want to have access to the array of plot abilities that Matplotlib offers, then you’ll want to know how to include Matplotlib plots within your application.

In this tutorial we’ll cover how to embed Matplotlib plots in your PyQt applications

Many other Python libraries — such as seaborn and pandas— make use of the Matplotlib backend for plotting. These plots can be embedded in PyQt5 in the same way shown here, and the reference to the axes passed when plotting. There is a pandas example at the end of this tutorial.

Installing Matplotlib

The following examples assume you have Matplotlib installed. If not you can install it as normal using Pip, with the following —

A simple example

The following minimal example sets up a Matplotlib canvas FigureCanvasQTAgg which creates the Figure and adds a single set of axes to it. This canvas object is also a QWidget and so can be embedded straight into an application as any other Qt widget.

Как вставить matplotlib в pyqtBasic plot with embedded Matplotlib

Plot controls

Plots from Matplotlib displayed in PyQt5 are actually rendered as simple (bitmap) images by the Agg backend. The FigureCanvasQTAgg class wraps this backend and displays the resulting image on a Qt widget. The effect of this architecture is that Qt is unaware of the positions of lines and other plot elements — only the x, y coordinates of any clicks and mouse movements over the widget.

However, support for handling Qt mouse events and transforming them into interactions on the plot is built into Matplotlib. This can be controlled through a custom toolbar which can be added to your applications alongside the plot. In this section we’ll look at adding these controls so we can zoom, pan and get data from embedded Matplotlib plots.

We’ll step through the changes.

Running the above code will produce the following window layout, showing the plot at the bottom and the controls on top as a toolbar.

Как вставить matplotlib в pyqtMatplotlib plot with Toolbar

The buttons provided by NavigationToolbar2QT allow the following actions —

A few of these configuration settings are shown below.

Как вставить matplotlib в pyqtMatplotlib figure options

Как вставить matplotlib в pyqtMatplotlib curves figure options

For more information on navigating and configuring Matplotlib plots, take a look at the official Matplotlib toolbar documentation.

Create GUI Applications with Python & Qt5
The easy way to create desktop applications

The complete guide to building GUI applications with PyQt5. From the basics of creating a desktop window to the key features you need to build real apps.

Как вставить matplotlib в pyqt

Downloadable ebook (PDF, ePub) & Complete Source code

To support developers in [[ countryRegion ]] I give a [[ localizedDiscount[couponCode] ]]% discount with the code [[ couponCode ]] — Enjoy!

For [[ activeDiscount.description ]] I’m giving a [[ activeDiscount.discount ]]% discount with the code [[ couponCode ]] — Enjoy!

Updating plots

Quite often in applications you’ll want to update the data shown in plots, whether in response to input from the user or updated data from an API. There are two ways to update plots in Matplotlib, either

If performance is important to your app it is recommended you do the latter, but the first is simpler.

Clear and redraw

We start with the simple clear-and-redraw method first below —

In this example we’ve moved the plotting to a update_plot method to keep it self-contained. In this method we take our ydata array and drop off the first value with [1:] then append a new random integer between 0 and 10. This has the effect of scrolling the data to the left.

In-place redraw

The changes required to update the plotted lines in-place are fairly minimal, requiring only an addition variable to store and retrieve the reference to the plotted line. The updated MainWindow code is shown below.

T> If you were drawing multiple lines you would probably want to use a list or dict data structure to store the multiple references and keep track of which is which.

Finally, we update the ydata data as we did before, rotating it to the left and appending a new random value. Then we either —

You could also use tuple-unpacking, picking off the first (and only) element in the list with —

If you run the resulting code, there will be no noticeable difference in performance between this and the previous method at this speed. However if you attempt to update the plot faster (e.g. down to every 10 msec) you’ll start to notice that clearing the plot and re-drawing takes longer, and the updates do not keep up with the timer. We can compare the two versions below —

Both using 100 msec timer, clear-and-redraw on the left, update-in-place on the right.

Both using 10 msec timer, clear-and-redraw on the left, update-in-place on the right.

Whether this performance difference is enough to matter in your application depends on what you’re building, and should be weighed against the added complication of keeping and managing the references to plotted lines.

Embedding plots from Pandas

Pandas is a Python package focused on working with table (data frames) and series data structures, which is particularly useful for data analysis workflows. It comes with built-in support for plotting with Matplotlib and here we’ll take a quick look at how to embed these plots into PyQt5. With this you will be able to start building PyQt5 data-analysis applications built around Pandas.

Pandas plotting functions are directly accessible from the DataFrame objects. The function signature is quite complex, giving a lot of options to control how the plots will be drawn.

The resulting plot generated through Pandas is shown below —

Как вставить matplotlib в pyqtPandas plot embedded in PyQt5

Just as before, you can add the Matplotlib toolbar and control support to plots generated using Pandas, allowing you to zoom/pan and modify them live. The following code combines our earlier toolbar example with the Pandas example.

Running this you should see the following window, showing a Pandas plot embedded in PyQt5 alongside the Matplotlib toolbar.

Как вставить matplotlib в pyqtPandas plot with Matplotlib toolbar

What’s next

In this tutorial we looked at how you can embed Matplotlib plots in your PyQt5 applications. Being able to use Matplotlib plots in your applications allows you to create custom data analysis and visualization tools from Python.

Matplotlib is a huge library and too big to cover in detail here. If you’re not familiar with Matplotlib plotting and want to give it a try, take a look at the documentation and example plots to see what is possible. If you are familiar with it you should now be able to put those skills to work in your PyQt5 apps!

If you found this tutorial helpful, please consider sharing it with your network.
Your support helps me to continue writing these tutorials. Thankyou!

Источник

Русские Блоги

Отображение графики, нарисованной matplotlib, в графическом интерфейсе, разработанном PyQt5

1. Как встроить matplotlib в PyQt5?

Подключите PyQt5 через класс matplotlib.backends.backend_qt5agg. В фактическом коде нам нужно добавить контент в справочный раздел:

Во-вторых, как использовать FigureCanvas и класс Figure

Обратитесь к соответствующему контенту, разработанному при использовании FigureCanvas и класса Figure для создания окна рисования графика:
[класс matplotlib.figure]https://matplotlib.org/api/figure_api.html
[серверный класс]https://matplotlib.org/api/index_backend_api.html
Конструктор Figure () используется для создания figure (), аналогичного Matlab или matplotlib.pyplot.

Другая функция: add_subplot (221)
Он используется для создания подзаголовков, как показано в подзаголовке Matlab (2,2,1), что означает, что всего есть 4 подзаголовка, и в настоящее время это первый подзаголовок. Конкретные приложения следующие:

Затем нарисуйте график в self.axes следующим образом:

=============================================
В приведенном выше введении показано, как рисовать графику с помощью рисунка и подзаголовка. Графику можно рисовать, но как отобразить ее в элементах управления графического интерфейса?

3. Как отображать графику в элементах управления Gui?

График: синусоида, self.axes.plot (t, s), представленный на рисунке
Графический интерфейс: три типа окон: виджет, диалог и MainWindow.
Элемент управления (компонент):
1) На странице виджета QTabWidget ()
2) графическое представление QGraphicsView
3) Элемент управления группового поля QgroupBox
4) Есть и другие элементы управления, которые можно использовать в качестве контейнеров пользовательского интерфейса.
[Поскольку созданный рисунок сам по себе является компонентом, он также является виджетом в PyQt, поэтому нам нужно только добавить созданный рисунок в контейнерный элемент управления в интерфейсе графического интерфейса, чтобы отобразить рисунок. 】

Затем создайте новый файл python для записи основной функциональной части, конкретный код выглядит следующим образом:

Результат такой:
Как вставить matplotlib в pyqt

Пример 2. На основе приведенного выше примера добавьте элемент управления TabWidget и отобразите нарисованную графику в элементе управления Tabwidget. [В основном изменить шестой шаг]

Результат:
Как вставить matplotlib в pyqt

Пример 3 Измените шестой шаг на основе примера 1. Добавьте окно просмотра QGraphicsView для отображения графики в поле GroupBox. Конкретные изменения заключаются в следующем:

Результат:
Как вставить matplotlib в pyqt

Из трех графиков результатов мы можем видеть, что использование GraphicsView в Примере 3 является пустой тратой места, и дисплей недостаточно заполнен, а эффект отображения примеров 1 и 2 лучше.

То же самое верно и для отображения в Widget и MainWindow, и я не буду приводить здесь примеры один за другим.

Источник

How to Embed Matplotlib Graph in PyQt5

In this PyQt5 article iam going to show you How to Embed Matplotlib Graph, so

before starting our main topic if your interested in Python GUI Development with different

Also you can check more Python GUI articles in the below links

Matplotlib is a Python 2D plotting library which produces publication quality figures in a variety of hardcopy formats and interactive environments across platforms. Matplotlib can be used in Python scripts, the Python and IPython shells, the Jupyter notebook, web application servers, and four graphical user interface toolkits.

Matplotlib tries to make easy things easy and hard things possible. You can generate plots, histograms, power spectra, bar charts, errorcharts, scatterplots, etc., with just a few lines of code. For examples, see the sample plots and thumbnail gallery.

For simple plotting the pyplot module provides a MATLAB-like interface, particularly when combined with IPython. For the power user, you have full control of line styles, font properties, axes properties, etc, via an object oriented interface or via a set of functions familiar to MATLAB users.

Installation

You can simple install matplotlib by using pip install matplotlib, or for more information about installation you can check the Installation Instruction.

Qt is set of cross-platform C++ libraries that implement high-level APIs for accessing many aspects of modern desktop and mobile systems. These include location and positioning services, multimedia, NFC and Bluetooth connectivity, a Chromium based web browser, as well as traditional UI development.

PyQt5 is a comprehensive set of Python bindings for Qt v5. It is implemented as more than 35 extension modules and enables Python to be used as an alternative application development language to C++ on all supported platforms including iOS and Android.

PyQt5 may also be embedded in C++ based applications to allow users of those applications to configure or enhance the functionality of those applications.

Installation

The GPL version of PyQt5 can be installed from PyPI:

Источник

Как вставить matplotlib в pyqt

Используем matplotlib для рисования графиков в PyQt5

Экспериментальная функция:

Ниже вы видите текст статьи по ссылке. По нему можно быстро понять ссылка достойна прочтения или нет

Просим обратить внимание, что текст по ссылке и здесь может не совпадать.

Installing Matplotlib

The following examples assume you have Matplotlib installed. If not you can install it as normal using Pip, with the following —

A simple example

The following minimal example sets up a Matplotlib canvas FigureCanvasQTAgg which creates the Figure and adds a single set of axes to it. This canvas object is also a QWidget and so can be embedded straight into an application as any other Qt widget.

Plot controls

Plots from Matplotlib displayed in PyQt5 are actually rendered as simple (bitmap) images by the Agg backend. The FigureCanvasQTAgg class wraps this backend and displays the resulting image on a Qt widget. The effect of this architecture is that Qt is unaware of the positions of lines and other plot elements — only the x, y coordinates of any clicks and mouse movements over the widget.

However, support for handling Qt mouse events and transforming them into interactions on the plot is built into Matplotlib. This can be controlled through a custom toolbar which can be added to your applications alongside the plot. In this section we’ll look at adding these controls so we can zoom, pan and get data from embedded Matplotlib plots.

We’ll step through the changes.

Running the above code will produce the following window layout, showing the plot at the bottom and the controls on top as a toolbar.

For more information on navigating and configuring Matplotlib plots, take a look at the official Matplotlib toolbar documentation.

Updating plots

Quite often in applications you’ll want to update the data shown in plots, whether in response to input from the user or updated data from an API. There are two ways to update plots in Matplotlib, either

If performance is important to your app it is recommended you do the latter, but the first is simpler. We start with the simple clear-and-redraw method first below —

Clear and redraw

In this example we’ve moved the plotting to a update_plot method to keep it self-contained. In this method we take our ydata array and drop off the first value with [1:] then append a new random integer between 0 and 10. This has the effect of scrolling the data to the left.

In-place redraw

The changes required to update the plotted lines in-place are fairly minimal, requiring only an addition variable to store and retrieve the reference to the plotted line. The updated MainWindow code is shown below.

T> If you were drawing multiple lines you would probably want to use a list or dict data structure to store the multiple references and keep track of which is which.

Finally, we update the ydata data as we did before, rotating it to the left and appending a new random value. Then we either —

You could also use tuple-unpacking, picking off the first (and only) element in the list with —

If you run the resulting code, there will be no noticeable difference in performance between this and the previous method at this speed. However if you attempt to update the plot faster (e.g. down to every 10 msec) you’ll start to notice that clearing the plot and re-drawing takes longer, and the updates do not keep up with the timer. We can compare the two versions below —

Both using 100 msec timer, clear-and-redraw on the left, update-in-place on the right.

Both using 10 msec timer, clear-and-redraw on the left, update-in-place on the right.

Whether this performance difference is enough to matter in your application depends on what you’re building, and should be weighed against the added complication of keeping and managing the references to plotted lines.

Embedding plots from Pandas

Pandas is a Python package focused on working with table (data frames) and series data structures, which is particularly useful for data analysis workflows. It comes with built-in support for plotting with Matplotlib and here we’ll take a quick look at how to embed these plots into PyQt5. With this you will be able to start building PyQt5 data-analysis applications built around Pandas.

Pandas plotting functions are directly accessible from the DataFrame objects. The function signature is quite complex, giving a lot of options to control how the plots will be drawn.

The resulting plot generated through Pandas is shown below —

Just as before, you can add the Matplotlib toolbar and control support to plots generated using Pandas, allowing you to zoom/pan and modify them live. The following code combines our earlier toolbar example with the Pandas example.

Running this you should see the following window, showing a Pandas plot embedded in PyQt5 alongside the Matplotlib toolbar.

Источник

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *