
With the growing demand for Data Science and Analytics skill sets, drawing graphics programmatically is a very popular task these days.
Are you looking for a simple way to visualize and analyze data programmatically, and build a nice GUI for them? What about harnessing the power of ChatGPT to help? We will show how you can do it easily by combining Python4Delphi, DelphiVCL4Python, and DelphiFMX4Python with the Matplotlib library. We will show the embedding of the Matplotlib library with other Python GUI builders as well.
Furthermore, we will employ LLMs (ChatGPT or GPT-3.5 and Bing Chat or Copilot that are powered by GPT-4) to provide us with more ideas to enrich our Python GUI-based apps. And we’re going to share the prompt examples (including the recommended prompts generated by Bing Chat or Copilot) and the source code to you via this post.
This article is written as a further development of the following articles:
This article also inspired by the following brilliant video by Eli Mapstead about how to employ ChatGPT to create Python GUI using numerous Python GUI frameworks:
And, if you are looking for a way to retrain your own GPT to empower your apps, read it here:
The following is the compilation of 20+ ChatGPT prompts (and their answers) to enrich the ideas of working with Python GUI builders and the Matplotlib library:
Table of Contents
1. What is Matplotlib?
GPT-4/Bing Chat/Copilot answers:

Matplotlib is a comprehensive library for creating static, animated, and interactive visualizations in Python. It can produce publication-quality figures in various formats and platforms, and can be used in scripts, shells, web applications, and graphical user interface toolkits. Matplotlib makes easy things easy and hard things possible. You can create plots, histograms, bar charts, scatter plots, pie charts, and many more types of visualizations with Matplotlib. You can also customize the visual style and layout of your figures, and make interactive figures that can zoom, pan, update, and respond to user events. Matplotlib is a community project maintained for and by its users, and you can join the community to get help, share your work, and contribute to the development of Matplotlib. For more information, you can visit the Matplotlib website, the Matplotlib documentation, or the Matplotlib PyPI page.
GPT-3.5/ChatGPT answers:

Matplotlib is a 2D plotting library for the Python programming language. It provides an object-oriented API for embedding plots into applications that use general-purpose GUI toolkits, such as Tkinter, wxPython, Qt, or GTK. Matplotlib can be used to generate a wide range of static, animated, and interactive plots in Python.
Key features of Matplotlib include:
1. Publication-Quality Plots
Matplotlib is capable of creating high-quality plots suitable for publication in scientific journals or presentations.
2. Wide Range of Plot Types
It supports a variety of plot types, including line plots, scatter plots, bar plots, histograms, 3D plots, and more.
3. Customization
Users have extensive control over the appearance of plots. You can customize colors, line styles, markers, labels, and more.
4. matplotlib.pyplot
Interface
Matplotlib provides a MATLAB-like interface through the pyplot
module, which simplifies the process of creating common plots.
5. Object-Oriented API
Matplotlib can be used in an object-oriented manner for more advanced customization and control over plots.
6. Integration with Jupyter Notebooks
Matplotlib integrates well with Jupyter Notebooks, allowing for the creation of inline plots that enhance the interactive data analysis experience.
7. Extensibility
It is extensible and allows users to create custom plots and themes.
8. Cross-Platform
Matplotlib is cross-platform and works on various operating systems, including Windows, macOS, and Linux.
Here’s a simple example of using Matplotlib to create a basic line plot:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
import matplotlib.pyplot as plt # Sample data x = [1, 2, 3, 4] y = [2, 4, 6, 8] # Create a line plot plt.plot(x, y) # Add labels and title plt.xlabel('X-axis') plt.ylabel('Y-axis') plt.title('Simple Line Plot') # Display the plot plt.show() |
This code creates a basic line plot with labeled axes and a title. Matplotlib is widely used in various fields, including scientific research, data analysis, and machine learning, for visualizing data and conveying insights.
Run the example above on the PyScripter IDE will give you the following output:

2. What are the main components of a Matplotlib plot?
GPT-4/Bing Chat/Copilot answers:

The main components of a Matplotlib plot are as follows:
- Figure: The container of the full plot and its parts. You can create a figure with
plt.figure()
. - Axes: The region of the figure where the data is plotted. You can create one or more axes in a figure with
fig.subplots()
. - Title: The title of the plot. You can set the title with
ax.set_title()
. - X and Y axis: The horizontal and vertical lines that define the coordinate system of the plot. You can access them with
ax.xaxis
andax.yaxis
. - Tick labels: The labels of the major and minor ticks on the axes. You can set them with
ax.xaxis.set_major_formatter()
andax.xaxis.set_minor_formatter()
for thex
axis, and similarly for they
axis. - Legend: Contains the labels of each plot element, such as lines, markers, etc. You can create a legend with
ax.legend()
. - Spine: The boundary of the axes. You can access them with
ax.spines
.
You can see an example of a Matplotlib plot with annotations of these components from their official documentation.
GPT-3.5/ChatGPT answers:

A Matplotlib plot typically consists of several key components, each contributing to the overall structure and appearance of the visualization. Here are the main components of a Matplotlib plot:
1. Figure
- The entire window or page in which the plot appears. The figure is the top-level container that holds all the elements of the plot. You can think of it as the canvas on which you create your visualizations.
2. Axes
- The region of the figure that actually displays the data. A figure can have one or more axes. Each axis represents a separate plot. Axes have X and Y axes (and possibly a Z axis in 3D plots) and can contain various graphical elements like lines, markers, text, etc.
3. Axis
- The number line that represents the scale of the plot. Axes have two (or three) of these, denoting the data range. Matplotlib automatically determines the axis limits based on the data, but you can customize them if needed.
4. Plotting Elements
- These include lines, markers, and other graphical elements that represent the data on the plot. The
plot
function is commonly used for creating line plots, while other functions likescatter
,bar
, etc., are used for different types of plots.
5. Title
- A title that provides information about the content of the plot. You can use the
title
function to set the title.
6. X-Axis Label and Y-Axis Label
- Labels for the X and Y axes that describe the type of data being displayed. These labels are set using the
xlabel
andylabel
functions.
7. Legend
- A legend is used to identify different elements on the plot. For example, if you have multiple lines or datasets, the legend helps to distinguish between them. You can add a legend using the
legend
function.
8. Grid
- Grid lines can be added to aid in reading values from the plot. You can enable the grid using the
grid
function.
9. Ticks and Tick Labels
- Ticks are the marks on the axis indicating specific data values, and tick labels are the text labels associated with these ticks. You can customize ticks and tick labels using functions like
xticks
andyticks
.
10. Colorbar (for Contour Plots)
- In contour plots, a colorbar is used to show the mapping of data values to colors. You can add a colorbar using the
colorbar
function.
These components collectively provide a flexible and customizable framework for creating a wide range of plots in Matplotlib. Depending on the complexity of your visualization, you may choose to customize and include different combinations of these components.
3. How can I customize the appearance of a plot in Matplotlib?
GPT-4/Bing Chat/Copilot answers:

There are several ways to customize the appearance of a plot in Matplotlib. You can modify the properties of the plot elements, such as line width, color, marker, label, etc. You can also change the layout and style of the plot, such as the title, axis, legend, grid, spine, etc. You can use the matplotlib.pyplot
module to access the functions and methods that control these aspects of the plot. For example, you can use plt.plot()
to create a line plot and pass arguments to customize the line, such as plt.plot(x, y, color='red', linewidth=2, linestyle='--', marker='o', label='line 1')
. You can also use plt.title()
, plt.xlabel()
, plt.ylabel()
, plt.legend()
, plt.grid()
, etc. to modify the plot title, axis labels, legend, grid, etc. For a full list of pyplot
functions, see the Pyplot tutorial.
Another way to customize the appearance of plots is to use style sheets. Style sheets are files that contain a set of predefined rcParams
that control the style of the plot, such as the color cycle, font, line style, etc. Matplotlib provides several built-in style sheets that you can use by calling plt.style.use('style_name')
, where style_name
is the name of the style sheet, such as ‘classic
’, ‘ggplot
’, ‘seaborn
’, etc. You can also create your own style sheets or modify the existing ones. For more information on style sheets, see the Customizing Matplotlib with style sheets and rcParams
page.
You can also use the matplotlib.rcParams
dictionary to directly modify the rcParams
at runtime. This allows you to change the default settings of Matplotlib for the current session. For example, you can use mpl.rcParams['lines.linewidth'] = 2
to set the default line width to 2
. You can also use the mpl.rc()
function to modify multiple settings in a single group at once, such as mpl.rc('lines', linewidth=2, linestyle='-.')
. You can also use the mpl.rc_context()
context manager or decorator to temporarily change the rcParams
within a block of code or a function. For more details on rcParams
, see the Customizing Matplotlib with style sheets and rcParams page.
If you want to learn more about how to customize your plots using Matplotlib, you can check out some of the following resources.
GPT-3.5/ChatGPT answers:

Matplotlib provides a wide range of options for customizing the appearance of plots. You can control various aspects, including colors, line styles, markers, labels, titles, legends, and more. Here are some common ways to customize the appearance of a plot in Matplotlib:
1. Colors
- You can specify colors using named colors (e.g., ‘
red
‘, ‘blue
‘), HTML color codes, or RGB tuples. The ‘color
’ parameter in most plotting functions can be used for this. For example:
1 |
plt.plot(x, y, color='green') |
2. Line Styles
- Control the style of the line with the ‘
linestyle
’ parameter. Common options include ‘-
‘, ‘--
‘, ‘-.
‘, ‘:
‘. For example:
1 |
plt.plot(x, y, linestyle='--') |
3. Markers
- Add markers to data points using the ‘
marker
’ parameter. Common options include ‘o
‘ (circle), ‘s
‘ (square), ‘^
‘ (triangle), etc. For example:
1 |
plt.plot(x, y, marker='o') |
4. Line Width
- Adjust the width of the line with the ‘
linewidth
’ parameter. For example:
1 |
plt.plot(x, y, linewidth=2) |
5. Transparency
- Set the transparency of elements using the ‘
alpha
’ parameter. This is particularly useful for overlapping elements. For example:
1 |
plt.scatter(x, y, alpha=0.5) |
6. Labels and Title
- Customize axis labels and the plot title using ‘
xlabel
’, ‘ylabel
’, and title functions. For example:
1 2 3 |
plt.xlabel('X-axis Label') plt.ylabel('Y-axis Label') plt.title('Plot Title') |
7. Legend
- Customize the legend using the ‘
legend
’ function. You can specify the location, add a title, and control other aspects. For example:
1 |
plt.legend(['Line 1', 'Line 2'], loc='upper right') |
8. Grid
- Display grid lines using the ‘
grid
’ function. For example:
1 |
plt.grid(True) |
9. Axis Limits
- Set specific limits for the X and Y axes using ‘
xlim
’ and ‘ylim
’. For example:
1 2 |
plt.xlim(0, 10) plt.ylim(0, 20) |
10. Tick Parameters
- Customize tick locations and labels using ‘
xticks
’ and ‘yticks
’. For example:
1 |
plt.xticks([0, 5, 10], ['Start', 'Middle', 'End']) |
11. Colorbar (for Contour Plots)
- Customize colorbar appearance for contour plots using the ‘
colorbar
’ function. For example:
1 |
plt.colorbar(label='Color Scale') |
12. Figure Size
- Adjust the size of the figure using the ‘
figsize
’ parameter when creating a figure. For example:
1 |
plt.figure(figsize=(8, 6)) |
These are just a few examples of the many customization options available in Matplotlib. The library provides extensive documentation, so you can refer to it for more details and options: Matplotlib Documentation.
4. How can I create different types of plots in Matplotlib, such as scatter plots or bar charts?
GPT-4/Bing Chat/Copilot answers:

To create different types of plots in Matplotlib, you need to use different functions and methods from the matplotlib.pyplot
module. For example, to create a scatter plot, you can use the scatter()
function, which takes two arrays of x
and y
values as arguments, and optionally other parameters to customize the appearance of the plot, such as color, size, shape, etc. To create a bar chart, you can use the bar()
function, which takes an array of x positions and an array of heights as arguments, and optionally other parameters to adjust the width, color, alignment, etc. of the bars. You can also use the barh()
function to create a horizontal bar chart.
Here is a simple example of how to create a scatter plot and a bar chart using Matplotlib:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
# Import the matplotlib.pyplot module import matplotlib.pyplot as plt # Create some sample data x = [1, 2, 3, 4, 5] y = [2, 4, 6, 8, 10] z = [10, 8, 6, 4, 2] # Create a scatter plot of x and y plt.scatter(x, y, color='red', marker='o', label='x vs y') # Create a bar chart of x and z plt.bar(x, z, color='blue', width=0.5, label='x vs z') # Add a title and axis labels plt.title('Example of Scatter Plot and Bar Chart') plt.xlabel('x') plt.ylabel('y and z') # Add a legend plt.legend() # Show the plot plt.show() |
This code will produce the following plot:

You can learn more about how to create different types of plots in Matplotlib from the following resources.
GPT-3.5/ChatGPT answers:

Matplotlib provides several functions for creating different types of plots. Here are examples of how to create scatter plots and bar charts using Matplotlib:
Scatter Plot
Scatter plots are useful for visualizing the relationship between two variables by displaying individual data points.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
import matplotlib.pyplot as plt # Sample data x = [1, 2, 3, 4, 5] y = [2, 4, 1, 5, 3] # Create a scatter plot plt.scatter(x, y, label='Scatter Plot', color='blue', marker='o') # Add labels and title plt.xlabel('X-axis') plt.ylabel('Y-axis') plt.title('Scatter Plot Example') # Add a legend plt.legend() # Show the plot plt.show() |
This code will produce the following plot:

Bar Chart
Bar charts are useful for comparing discrete categories of data.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
import matplotlib.pyplot as plt # Sample data categories = ['Category A', 'Category B', 'Category C', 'Category D'] values = [3, 7, 2, 5] # Create a bar chart plt.bar(categories, values, color='green') # Add labels and title plt.xlabel('Categories') plt.ylabel('Values') plt.title('Bar Chart Example') # Show the plot plt.show() |
This code will produce the following plot:

These are basic examples, and you can customize the appearance of these plots as discussed in the previous responses. Matplotlib offers various functions for creating different types of plots, including line plots, histograms, pie charts, box plots, and more. Depending on your data and the type of visualization you need, you can choose the appropriate Matplotlib function and customize it accordingly. Refer to the Matplotlib documentation for a comprehensive list of plot types and customization options: Matplotlib Documentation.
5. Can Matplotlib be used for 3D plotting?
GPT-4/Bing Chat/Copilot answers:

Yes, Matplotlib can be used for 3D plotting. Matplotlib has a toolkit called mplot3d
that allows you to create various types of 3D plots, such as line plots, scatter plots, surface plots, contour plots, wireframe plots, etc. You can import the mplot3d
toolkit with the following statement:
1 |
from mpl_toolkits import mplot3d |
To create a 3D plot, you need to create a figure and an axes
object with the projection='3d'
argument. For example:
1 2 |
fig = plt.figure() ax = plt.axes(projection='3d') |
Then you can use the methods of the axes object to plot your data in 3D. For example, you can use ax.plot3D()
to plot a 3D line, ax.scatter3D()
to plot a 3D scatter, ax.plot_surface()
to plot a 3D surface, etc. You can also customize the appearance and style of your 3D plots using the same functions and parameters as in 2D plots, such as ax.set_title()
, ax.set_xlabel()
, ax.set_ylabel()
, ax.set_zlabel()
, ax.legend()
, plt.style.use()
, etc.
Fix the code above and run it on the PyScripter IDE will give you the following output:

For more information and examples on how to use Matplotlib for 3D plotting, you can check out the following resources[a][b][c][d][e].
GPT-3.5/ChatGPT answers:

Yes, Matplotlib has a 3D plotting toolkit called mplot3d
that allows you to create a variety of 3D plots. This toolkit provides functions for creating 3D scatter plots, line plots, surface plots, and more. To use the 3D plotting capabilities in Matplotlib, you need to import the Axes3D
class from the mpl_toolkits.mplot3d
module.
Here’s a simple example of creating a 3D scatter plot:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D # Sample data x = [1, 2, 3, 4, 5] y = [2, 3, 4, 5, 6] z = [5, 6, 7, 8, 9] # Create a 3D scatter plot fig = plt.figure() ax = fig.add_subplot(111, projection='3d') ax.scatter(x, y, z, c='r', marker='o') # Add labels ax.set_xlabel('X-axis') ax.set_ylabel('Y-axis') ax.set_zlabel('Z-axis') # Show the plot plt.show() |
The code above will produce the following plot:

In this example, the scatter
function from the Axes3D
class is used to create a 3D scatter plot. The projection='3d'
parameter when creating the subplot indicates that it’s a 3D plot.
You can also create 3D line plots and surface plots using the plot
and plot_surface
functions, respectively. The mplot3d
toolkit provides a range of options for customizing 3D plots, such as setting viewing angles, adding color maps, and more.
Here’s a simple example of creating a 3D surface plot:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
import matplotlib.pyplot as plt import numpy as np from mpl_toolkits.mplot3d import Axes3D # Create a meshgrid for the surface plot x = np.linspace(-5, 5, 100) y = np.linspace(-5, 5, 100) X, Y = np.meshgrid(x, y) Z = np.sin(np.sqrt(X**2 + Y**2)) # Create a 3D surface plot fig = plt.figure() ax = fig.add_subplot(111, projection='3d') ax.plot_surface(X, Y, Z, cmap='viridis') # Add labels ax.set_xlabel('X-axis') ax.set_ylabel('Y-axis') ax.set_zlabel('Z-axis') # Show the plot plt.show() |
Run the example above on the PyScripter IDE will give you the following output:

This example demonstrates how to create a 3D surface plot of the sine function over a meshgrid. The plot_surface
function is used for this purpose.
6. What are some common errors when using Matplotlib?
GPT-4/Bing Chat/Copilot answers:

Matplotlib is a powerful Python library for creating various types of plots and visualizations. However, it may also encounter some errors or issues when using it. Here are some of the common errors when using Matplotlib and how to solve them:
ImportError: No module named ‘matplotlib’
: This error occurs when Matplotlib is not installed properly or when the Python version does not match the Matplotlib version. To fix this error, you need to install Matplotlib usingpip install matplotlib
orpip3 install matplotlib
, depending on your Python version. You can also check your Python and Matplotlib versions usingpython --version
andpip show matplotlib
[a].ValueError: setting an array element with a sequence
: This error occurs when Matplotlib tries to plot an array that contains nested arrays or lists, which are not supported by Matplotlib. To fix this error, you need to flatten the array or convert it to a NumPy array usingnp.array()
ornp.ravel()
[b].ValueError: Illegal argument(s) to subplot
: This error occurs when Matplotlib tries to create a subplot with invalid arguments. To fix this error, you need to pass three mandatory arguments tosubplot()
, which are the number of rows, the number of columns, and the index of the subplot. For example,subplot(2, 2, 1)
creates a 2×2 grid of subplots and selects the first one[c].AttributeError: ‘module’ object has no attribute ‘Image’
: This error occurs when Matplotlib is imported incorrectly or when there is a name conflict with another module. To fix this error, you need to import Matplotlib usingfrom matplotlib import pyplot as plt
orimport matplotlib.pyplot as plt
.
GPT-3.5/ChatGPT answers:

Using Matplotlib can sometimes lead to common errors, and troubleshooting them is an essential part of working with the library. Here are some common errors that users may encounter when working with Matplotlib:
1. Import Errors
- If Matplotlib is not installed, you will get an
ImportError
. Ensure that Matplotlib is installed using:
1 |
pip install matplotlib |
2. Plot Not Displaying
- If you are running a script and the plot does not appear, make sure to include the
plt.show()
function at the end of your script.
3. Plotting Inconsistencies
- Inconsistencies in the plot appearance may be caused by using different backends or issues with the rendering. You can try specifying a backend explicitly using
matplotlib.use('backend')
before importingpyplot
.
4. Jupyter Notebook Display Issues
- In Jupyter notebooks, make sure to use
%matplotlib inline
to ensure that plots are displayed correctly in the output cell.
5. Incorrect Data Dimensions
- When plotting, ensure that the dimensions of your data arrays match. For example, if you’re plotting two arrays, they should have the same length.
6. Incorrect Usage of Functions
- Check the documentation for the correct usage of Matplotlib functions. Common mistakes include using incorrect parameters or providing data in the wrong format.
7. Problems with Fonts
- Font-related errors may occur when Matplotlib cannot find the specified font. Ensure that the specified font is installed on your system or provide a valid path to the font file.
8. Backend Issues
- Some features may not be supported by all backends. If you encounter issues with a specific feature, consider changing the backend using
matplotlib.use('backend')
.
9. Color Specification Errors
- When specifying colors, ensure that you use valid color names, hex codes, or RGB tuples. Incorrect color specifications can lead to errors.
10. Missing Axes or Subplots
- If you’re working with multiple plots, ensure that you are using the correct axes or subplots. Mistakes in referencing axes can result in unexpected behavior.
11. Memory Errors with Large Datasets
- When working with large datasets, you may encounter memory errors. Consider downsampling or using techniques to handle large data efficiently.
12. Outdated Matplotlib Version
- Ensure that you are using an up-to-date version of Matplotlib. You can update it using:
1 |
pip install --upgrade matplotlib |
13. Interactivity Issues
- If you are using interactive features, such as zooming or panning, make sure that your backend supports them, and you are using the correct syntax.
14. Issues with 3D Plots
- When working with 3D plots, be cautious about setting appropriate viewing angles, as inappropriate angles can lead to plots not being visible.
If you encounter an error, reading the error message and checking the Matplotlib documentation and community forums can often help identify the issue. Additionally, debugging tools and techniques, such as print statements and stepping through code, can assist in troubleshooting.
7. Can you show me the Python code to use Matplotlib with Python4Delphi?
GPT-4/Bing Chat/Copilot answers:

Sure, I can show you an example of how to use Matplotlib with Python4Delphi. Python4Delphi is a set of tools that allows you to work with Python scripts, modules, and types in Delphi. Matplotlib is a library for creating various types of plots and visualizations in Python. To use Matplotlib with Python4Delphi, you need to do the following steps:
- Install Matplotlib using
pip install matplotlib
orpip3 install matplotlib
, depending on your Python version. - Import the Python4Delphi components from the
PythonEngine
andPythonGUIInputOutput
units in your Delphi project. - Drop a
TPythonEngine
, aTPythonGUIInputOutput
, and aTPythonModule
components on your form. - Set the
Output
property of theTPythonEngine
component to theTPythonGUIInputOutput
component. - Set the
Engine
property of theTPythonGUIInputOutput
component to theTPythonEngine
component. - Set the
Engine
andModule
properties of theTPythonModule
component to theTPythonEngine
andMainModule
components, respectively. - Write your Python code that uses Matplotlib in the
Strings
property of theTPythonModule
component. For example, you can use the following code to create a simple line plot:
1 2 3 4 5 6 7 8 9 10 |
import matplotlib.pyplot as plt x = [1, 2, 3, 4, 5] y = [2, 4, 6, 8, 10] plt.plot(x, y) plt.title('Example of Line Plot') plt.xlabel('x') plt.ylabel('y') plt.show() |
- Run your Delphi application and execute the Python code using the
ExecStrings
method of theTPythonEngine
component. For example, you can use the following code to execute the Python code when a button is clicked:
1 2 3 4 |
procedure TForm1.Button1Click(Sender: TObject); begin PythonEngine1.ExecStrings(PythonModule1.Strings); end; |
- A new window will pop up with the Matplotlib plot. You can interact with the plot using the toolbar buttons, such as zoom, pan, save, etc.
You can learn more about how to use Matplotlib with Python4Delphi from the following resources[a][b][c][d].
GPT-3.5/ChatGPT answers:

Certainly! To use Matplotlib with Python4Delphi, you’ll need to integrate the Python4Delphi components with Matplotlib. Python4Delphi provides a convenient way to embed Python into Delphi or C++ Builder applications.
Here is a simple example demonstrating how to use Matplotlib with Python4Delphi. Note that you need to have Python and Matplotlib installed on your system.
1. Install Python4Delphi: You can download it from the official GitHub repository: Python4Delphi.
2. Install Matplotlib: Open a command prompt and run the following command:
1 |
pip install matplotlib |
Now, let’s create a simple Delphi or C++ Builder application that uses Python4Delphi to plot a basic Matplotlib chart.
Delphi (Object Pascal) Example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 |
unit MainForm; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, PythonEngine, PythonGUIInputOutput, PythonDelphiVar, WrapDelphi, Vcl.ExtCtrls; type TForm1 = class(TForm) PythonEngine1: TPythonEngine; PythonGUIInputOutput1: TPythonGUIInputOutput; Button1: TButton; Panel1: TPanel; procedure Button1Click(Sender: TObject); private { Private declarations } public { Public declarations } end; var Form1: TForm1; implementation {$R *.dfm} procedure TForm1.Button1Click(Sender: TObject); begin // Execute Python code to plot a simple graph using Matplotlib PythonEngine1.ExecStrings( // 'import matplotlib.pyplot as plt' + sLineBreak + 'import numpy as np' + sLineBreak + 'x = np.linspace(0, 2*np.pi, 100)' + sLineBreak + 'y = np.sin(x)' + sLineBreak + 'plt.plot(x, y)' + sLineBreak + 'plt.xlabel("X-axis")' + sLineBreak + 'plt.ylabel("Y-axis")' + sLineBreak + 'plt.title("Matplotlib Plot")' + sLineBreak + 'plt.show()' ); end; end. |
In this example, we have a Delphi form with a button (Button1
). When the button is clicked, it executes Python code using the PythonEngine1.ExecStrings
method to create a simple sine wave plot using Matplotlib.
Make sure to set the appropriate properties of the PythonEngine1
component, like Executable
, to point to your Python executable.
This Delphi form can be dropped onto a Delphi application and executed. When you click the button, it will invoke Python and generate a Matplotlib plot.
8. Can you show me the Python code to use Matplotlib with DelphiVCL4Python?
GPT-4/Bing Chat/Copilot answers:

Sure, I can show you an example of how to use Matplotlib with DelphiVCL4Python. DelphiVCL4Python is a Python module that allows you to use Delphi’s VCL GUI framework in your Python applications[a]. Matplotlib is a library for creating various types of plots and visualizations in Python[b]. To use Matplotlib with DelphiVCL4Python, you need to do the following steps:
- Install Matplotlib using
pip install matplotlib
orpip3 install matplotlib
, depending on your Python version. - Install DelphiVCL4Python using
pip install delphivcl
orpip3 install delphivcl
, depending on your Python version. - Import the DelphiVCL4Python components from the
delphivcl
module in your Python script. - Create a VCL form and add a
TPanel
component to it. - Create a Matplotlib figure and an axes object using the
plt.subplots()
function. - Plot your data using the methods of the axes object, such as
ax.plot()
,ax.scatter()
,ax.bar()
, etc. - Embed the Matplotlib figure into the TPanel using the
delphivcl.MatplotlibPanel
class. - Show the VCL form using the
delphivcl.Application.Run()
function.
Here is a simple example of how to create a line plot using Matplotlib and DelphiVCL4Python:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 |
# Import the delphivcl module import delphivcl # Import the matplotlib.pyplot module import matplotlib.pyplot as plt # Create a VCL form form = delphivcl.Form() # Set the form caption and size form.Caption = 'Matplotlib Example' form.SetBounds(100, 100, 600, 400) # Create a TPanel on the form panel = delphivcl.Panel(form) # Set the panel alignment and border style panel.Align = delphivcl.alClient panel.BorderStyle = delphivcl.bsSingle # Create some sample data x = [1, 2, 3, 4, 5] y = [2, 4, 6, 8, 10] # Create a Matplotlib figure and an axes object fig, ax = plt.subplots() # Plot the data as a line ax.plot(x, y) # Set the plot title and axis labels ax.set_title('Example of Line Plot') ax.set_xlabel('x') ax.set_ylabel('y') # Embed the Matplotlib figure into the panel mpl_panel = delphivcl.MatplotlibPanel(panel, fig) # Show the form delphivcl.Application.Run() |
GPT-3.5/ChatGPT answers:

DelphiVCL4Python is a tool that allows you to embed Python code within a Delphi application using the VCL (Visual Component Library). To use Matplotlib with DelphiVCL4Python, you’ll need to follow a similar approach to the one used with Python4Delphi.
Here’s a basic example demonstrating how to create a DelphiVCL4Python application that utilizes Matplotlib for plotting:
1. Install DelphiVCL4Python: You can find it on GitHub: DelphiVCL4Python.
2. Install Matplotlib: Open a command prompt and run the following command:
1 |
pip install matplotlib |
Now, let’s create a simple Delphi application that uses DelphiVCL4Python to run Python code for plotting with Matplotlib.
Delphi Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 |
unit MainForm; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, PythonEngine, Vcl.PythonGUIInputOutput, Vcl.Buttons, Vcl.DBCtrls, Vcl.ExtCtrls; type TForm1 = class(TForm) PythonEngine1: TPythonEngine; PythonGUIInputOutput1: TPythonGUIInputOutput; PythonModule1: TPythonModule; btnRunPythonCode: TBitBtn; Panel1: TPanel; procedure btnRunPythonCodeClick(Sender: TObject); private { Private declarations } Public { Public declarations } end; var Form1: TForm1; implementation {$R *.dfm} procedure TForm1.btnRunPythonCodeClick(Sender: TObject); begin // Execute Python code to plot a simple graph using Matplotlib PythonEngine1.ExecStrings( 'import matplotlib.pyplot as plt' + sLineBreak + 'import numpy as np' + sLineBreak + 'x = np.linspace(0, 2*np.pi, 100)' + sLineBreak + 'y = np.sin(x)' + sLineBreak + 'plt.plot(x, y)' + sLineBreak + 'plt.xlabel("X-axis")' + sLineBreak + 'plt.ylabel("Y-axis")' + sLineBreak + 'plt.title("Matplotlib Plot")' + sLineBreak + 'plt.show()' ); end; end. |
This Delphi form contains a button (btnRunPythonCode
). When you click the button, it executes Python code using the PythonEngine1.ExecStrings
method. The Python code creates a simple sine wave plot using Matplotlib.
Ensure that the properties of PythonEngine1
are set correctly, such as the Executable
property pointing to your Python executable.
This Delphi form can be added to a Delphi application, and when you run it, clicking the button will invoke Python and generate a Matplotlib plot.
9. Can you show me the Python code to use Matplotlib with DelphiFMX4Python?
GPT-4/Bing Chat/Copilot answers:

Sure, I can generate some Python code to use Matplotlib with DelphiFMX4Python. Matplotlib is a Python library for creating static, animated, and interactive visualizations. DelphiFMX4Python is a Python module powered by Delphi’s FireMonkey framework, which supports Windows, MacOS, Linux, and Android GUI development.
Here is an example of how to create a simple plot with Matplotlib on a DelphiFMX4Python app:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 |
# Import the delphifmx module import delphifmx # Create a form with a panel and an image form = delphifmx.TForm() panel = delphifmx.TPanel(form) panel.Align = delphifmx.TAlignLayout.Client image = delphifmx.TImage(panel) image.Align = delphifmx.TAlignLayout.Client # Import the matplotlib module import matplotlib.pyplot as plt # Create some data to plot x = [1, 2, 3, 4, 5] y = [2, 4, 6, 8, 10] # Create a figure and an axes fig, ax = plt.subplots() # Plot the data on the axes ax.plot(x, y) # Save the figure to a file fig.savefig('plot.png') # Load the file into the image image.Bitmap.LoadFromFile('plot.png') # Show the form form.Show() |
I hope this helps you understand how to use Matplotlib with DelphiFMX4Python. You can find more information and examples on the GitHub repositories for DelphiFMX4Python and Matplotlib. You can also use the Delphi4PythonExporter tool to design your GUI forms with VCL or FireMonkey and export them to Python. Happy coding! 😊
GPT-3.5/ChatGPT answers:

DelphiFMX4Python is a framework that allows you to embed Python code within a Delphi FireMonkey application. Similar to the previous examples, you can use Matplotlib with DelphiFMX4Python by executing Python code that includes Matplotlib plotting commands.
Here’s a simple example demonstrating how to create a Delphi FireMonkey application with DelphiFMX4Python that utilizes Matplotlib for plotting:
1. Install DelphiFMX4Python: You can find it on GitHub: DelphiFMX4Python.
2. Install Matplotlib: Open a command prompt and run the following command:
1 |
pip install matplotlib |
Now, let’s create a simple Delphi FireMonkey application that uses DelphiFMX4Python to run Python code for plotting with Matplotlib.
Delphi Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 |
unit MainForm; interface uses System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants, FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs, FMX.StdCtrls, FMX.Edit, FMX.Controls.Presentation, FMX.ScrollBox, FMX.Memo, PythonEngine, PythonGUIInputOutput, WrapDelphi, WrapFMX, FMX.Pickers, FMX.Layouts; type TForm1 = class(TForm) PythonEngine1: TPythonEngine; PythonGUIInputOutput1: TPythonGUIInputOutput; PythonModule1: TPythonModule; btnRunPythonCode: TButton; Memo1: TMemo; ToolBar1: TToolBar; Label1: TLabel; procedure btnRunPythonCodeClick(Sender: TObject); private { Private declarations } Public { Public declarations } end; var Form1: TForm1; implementation {$R *.fmx} procedure TForm1.btnRunPythonCodeClick(Sender: TObject); begin // Execute Python code to plot a simple graph using Matplotlib PythonEngine1.ExecStrings( 'import matplotlib.pyplot as plt' + sLineBreak + 'import numpy as np' + sLineBreak + 'x = np.linspace(0, 2*np.pi, 100)' + sLineBreak + 'y = np.sin(x)' + sLineBreak + 'plt.plot(x, y)' + sLineBreak + 'plt.xlabel("X-axis")' + sLineBreak + 'plt.ylabel("Y-axis")' + sLineBreak + 'plt.title("Matplotlib Plot")' + sLineBreak + 'plt.show()' ); end; end. |
In this example, the Delphi form (Form1
) contains a TMemo
component to display the Python code and a TButton
component (btnRunPythonCode
) to execute the Python code. The Python code is the same as in the previous examples and creates a simple sine wave plot using Matplotlib.
Make sure that the properties of PythonEngine1
are set correctly, such as the Executable
property pointing to your Python executable.
This Delphi FireMonkey form can be added to a FireMonkey application, and when you run it, clicking the button will invoke Python and generate a Matplotlib plot.
If you found that the ChatGPT and Bing Chat answers for points 7, 8, and 9 are not really satisfying, please refer to the following articles for the successful use cases of integration between Delphi and Python’s Matplotlib:
10. Can you show me the Python code to use Matplotlib with Tkinter?
GPT-4/Bing Chat/Copilot answers:

Sure, I can show you an example of how to use Matplotlib with Tkinter. Tkinter is a standard Python module for creating graphical user interfaces. Matplotlib is a library for creating various types of plots and visualizations in Python. To use Matplotlib with Tkinter, you need to do the following steps:
- Import the
matplotlib.pyplot
module and the Tkinter module in your Python script. - Create a Tkinter window and a Tkinter frame to hold the plot.
- Create a Matplotlib figure and an axes object using the
plt.subplots()
function. - Plot your data using the methods of the axes object, such as
ax.plot()
,ax.scatter()
,ax.bar()
, etc. - Embed the Matplotlib figure into the Tkinter frame using the
FigureCanvasTkAgg
class from thematplotlib.backends.backend_tkagg
module. - Optionally, add a Matplotlib toolbar to the Tkinter window using the
NavigationToolbar2Tk
class from the same module.
Here is a simple example of how to create a line plot using Matplotlib and Tkinter:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 |
# Import the matplotlib.pyplot and tkinter modules import matplotlib.pyplot as plt import tkinter as tk # Create a Tkinter window window = tk.Tk() window.title('Matplotlib Example') window.geometry('500x500') # Create a Tkinter frame frame = tk.Frame(window) frame.pack() # Create some sample data x = [1, 2, 3, 4, 5] y = [2, 4, 6, 8, 10] # Create a Matplotlib figure and an axes object fig, ax = plt.subplots() # Plot the data as a line ax.plot(x, y) # Set the plot title and axis labels ax.set_title('Example of Line Plot') ax.set_xlabel('x') ax.set_ylabel('y') # Embed the Matplotlib figure into the Tkinter frame canvas = FigureCanvasTkAgg(fig, master=frame) canvas.draw() canvas.get_tk_widget().pack() # Add a Matplotlib toolbar to the Tkinter window toolbar = NavigationToolbar2Tk(canvas, window) toolbar.update() canvas.get_tk_widget().pack() # Show the Tkinter window window.mainloop() |
You can learn more about how to use Matplotlib with Tkinter from the following resources[a][b][c].
It throws the following error: “NameError: name 'FigureCanvasTkAgg' is not defined
“. Can you help me to fix that?

This error means that Python cannot find the definition of the FigureCanvasTkAgg
class, which is used to embed Matplotlib figures into Tkinter frames. There are a few possible reasons for this error:
- You did not import the
FigureCanvasTkAgg
class from thematplotlib.backends.backend_tkagg
module. To fix this, you need to add the following statement at the beginning of your script:
1 |
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg |
- You misspelled the name of the class or the module. To fix this, you need to check the spelling and case of the class and the module, and make sure they match the documentation[a].
- You have a name conflict with another module or variable that uses the same name as the class or the module. To fix this, you need to rename or avoid using the conflicting name in your script.
You can learn more about how to use the FigureCanvasTkAgg
class and other Matplotlib backends from the following resources[a][b][c].
It throws the following error now: “NameError: name 'NavigationToolbar2Tk' is not defined
“. Can you help me to fix that?

This error means that Python cannot find the definition of the NavigationToolbar2Tk
class, which is used to add a Matplotlib toolbar to the Tkinter window. There are a few possible reasons for this error:
- You did not import the
NavigationToolbar2Tk
class from thematplotlib.backends.backend_tkagg
module. To fix this, you need to add the following statement at the beginning of your script:
1 |
from matplotlib.backends.backend_tkagg import NavigationToolbar2Tk |
- You misspelled the name of the class or the module. To fix this, you need to check the spelling and case of the class and the module, and make sure they match the documentation[a].
- You have a name conflict with another module or variable that uses the same name as the class or the module. To fix this, you need to rename or avoid using the conflicting name in your script.
You can learn more about how to use the NavigationToolbar2Tk
class and other Matplotlib backends from the following resources[a][b][c].
Fix the code above and it will produce the following output:

GPT-3.5/ChatGPT answers:

Certainly! To use Matplotlib with Tkinter, you’ll need to embed Matplotlib plots within a Tkinter application. Here’s a simple example of a Python script that uses Tkinter for the GUI and Matplotlib for plotting:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 |
import tkinter as tk from tkinter import ttk from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg from matplotlib.figure import Figure import numpy as np def plot_matplotlib(): # Create sample data x = np.linspace(0, 2 * np.pi, 100) y = np.sin(x) # Create a Matplotlib figure fig = Figure(figsize=(5, 4), dpi=100) ax = fig.add_subplot(1, 1, 1) ax.plot(x, y, label='Sine Wave') ax.set_xlabel('X-axis') ax.set_ylabel('Y-axis') ax.set_title('Matplotlib Plot') ax.legend() # Embed the Matplotlib figure in Tkinter canvas = FigureCanvasTkAgg(fig, master=frame) canvas.draw() canvas.get_tk_widget().pack(side=tk.TOP, fill=tk.BOTH, expand=1) # Create the main Tkinter window root = tk.Tk() root.title("Tkinter with Matplotlib") # Create a frame within the window frame = ttk.Frame(root) frame.pack(expand=True, fill=tk.BOTH) # Create a button to trigger Matplotlib plot button = ttk.Button(frame, text="Plot Matplotlib", command=plot_matplotlib) button.pack(side=tk.BOTTOM) # Start the Tkinter event loop root.mainloop() |
This script creates a Tkinter window with a button. When the button is clicked, a Matplotlib plot of a sine wave is displayed within the Tkinter window. The Matplotlib figure is embedded using FigureCanvasTkAgg
.
Save the script to a file (e.g., tkinter_matplotlib.py
) and run it using a Python interpreter. Click the “Plot Matplotlib
” button to see the Matplotlib plot embedded in the Tkinter window.
Run the example above on the PyScripter IDE will give you the following output:


11. Can you show me the Python code to use Matplotlib with PyQt?
GPT-4/Bing Chat/Copilot answers:

Certainly! To incorporate Matplotlib plots within a PyQt5 application, follow these steps:
1. Install Matplotlib (if not already installed)
Make sure you have Matplotlib installed. You can install it using the following command:
1 |
pip install matplotlib |
2. Create a Simple Example
Below is a minimal example that sets up a Matplotlib canvas using FigureCanvasQTAgg
. This canvas creates a figure and adds a single set of axes to it. The canvas is also a QWidget
, allowing it to be embedded directly into a PyQt application like any other Qt widget.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
import sys import matplotlib matplotlib.use('Qt5Agg') # Set the backend to Qt5Agg from PyQt5 import QtCore, QtWidgets from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg from matplotlib.figure import Figure class MplCanvas(FigureCanvasQTAgg): def __init__(self, parent=None, width=5, height=4, dpi=100): fig = Figure(figsize=(width, height), dpi=dpi) self.axes = fig.add_subplot(111) super().__init__(fig) class MainWindow(QtWidgets.QMainWindow): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) # Create the Matplotlib FigureCanvas object sc = MplCanvas(self, width=5, height=4, dpi=100) sc.axes.plot([0, 1, 2, 3, 4], [10, 1, 20, 3, 40]) # Example data self.setCentralWidget(sc) self.show() app = QtWidgets.QApplication(sys.argv) w = MainWindow() app.exec_() |
In this example, we add our MplCanvas
widget as the central widget in the window using .setCentralWidget()
. This means it will occupy the entire window and resize accordingly.
3. Run Your PyQt Application
Integrate this Python script into your PyQt application. The provided code snippet creates a simple plot with custom data. You can customize it further to suit your specific needs.
Remember that Matplotlib offers a rich assortment of plots, and embedding them within your PyQt application allows you to leverage its powerful visualization capabilities. Happy plotting! 📊🐍
For more details, explore the official PyQt5 tutorial on plotting with Matplotlib and discover additional features and customization options[a][b].
Run the example above on the PyScripter IDE will give you the following output:

GPT-3.5/ChatGPT answers:

Certainly! Using Matplotlib with PyQt involves embedding Matplotlib plots within PyQt GUI applications. Below is a simple example demonstrating how to create a PyQt application that includes a Matplotlib plot:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 |
import sys from PyQt5.QtWidgets import QApplication, QMainWindow, QVBoxLayout, QWidget, QPushButton from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas from matplotlib.figure import Figure import numpy as np class MainWindow(QMainWindow): def __init__(self): super().__init__() self.setWindowTitle("Matplotlib with PyQt") self.setGeometry(100, 100, 800, 600) # Create a central widget central_widget = QWidget() self.setCentralWidget(central_widget) # Create a layout for the central widget layout = QVBoxLayout() central_widget.setLayout(layout) # Create a Matplotlib figure self.figure = Figure(figsize=(5, 4), dpi=100) self.canvas = FigureCanvas(self.figure) layout.addWidget(self.canvas) # Create a button to update the plot button = QPushButton("Update Plot") button.clicked.connect(self.update_plot) layout.addWidget(button) # Initial plot self.update_plot() def update_plot(self): # Clear the previous plot self.figure.clear() # Generate data x = np.linspace(0, 10, 100) y = np.sin(x) # Plot data ax = self.figure.add_subplot(111) ax.plot(x, y) ax.set_xlabel('X-axis') ax.set_ylabel('Y-axis') ax.set_title('Matplotlib Plot') # Update canvas self.canvas.draw() if __name__ == '__main__': app = QApplication(sys.argv) window = MainWindow() window.show() sys.exit(app.exec_()) |
In this example:
- We create a PyQt
QMainWindow
namedMainWindow
. - Inside
MainWindow
, we create a central widget (QWidget
) and add a vertical layout (QVBoxLayout
) to it. - We create a
Figure
and aFigureCanvas
from Matplotlib. The canvas is added to the layout. - We add a
QPushButton
to the layout, which when clicked calls theupdate_plot()
method. - The
update_plot()
method clears the previous plot, generates new data, plots it, and updates the canvas.
To run this code, make sure you have both PyQt5 and Matplotlib installed:
1 |
pip install PyQt5 matplotlib |
Save the code in a file (e.g., matplotlib_with_pyqt.py
) and run it using a Python interpreter. You should see a window with a Matplotlib plot and a button. Clicking the button will update the plot with new data.

12. Can you show me the Python code to use Matplotlib with Kivy?
GPT-4/Bing Chat/Copilot answers:

Certainly! To integrate Matplotlib with Kivy, you can create interactive plots within your Kivy application. Here are a few approaches:
1. Using FigureCanvasKivyAgg
Below is an example that demonstrates how to add a Matplotlib figure to a Kivy app using FigureCanvasKivyAgg
. This approach allows you to display a Matplotlib plot directly within your Kivy interface:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 |
from kivy.lang import Builder from kivymd.app import MDApp from kivy.uix.floatlayout import FloatLayout from kivy.garden.matplotlib.backend_kivyagg import FigureCanvasKivyAgg import matplotlib.pyplot as plt class MyApp(MDApp): def build(self): layout = Builder.load_string(""" BoxLayout: orientation: 'vertical' BoxLayout: id: layout """) # Example data signal = [7, 89.6, 45.56, 34] signal = np.array(signal) # Create a simple plot plt.plot(signal) plt.xlabel('Time (s)') plt.ylabel('Signal (norm)') plt.grid(True, color='lightgray') # Add the Matplotlib canvas to the Kivy layout layout.ids.layout.add_widget(FigureCanvasKivyAgg(plt.gcf())) return layout if __name__ == '__main__': MyApp().run() |
This code snippet creates a Kivy app with a Matplotlib plot embedded in it. Adjust the data and customize the plot as needed.
2. Using Custom Widgets
You can create custom Kivy widgets that encapsulate Matplotlib plots. For example, the kivy_matplotlib
project provides a simple widget to display Matplotlib plots within Kivy. You can install it using pip install kivy-matplotlib-widget
and then use it in your Kivy app:
1 2 3 4 5 6 7 8 9 10 11 12 13 |
import matplotlib as mpl from kivy_matplotlib import MatplotFigure from kivy.base import runTouchApp # Create a Matplotlib figure fig = mpl.figure.Figure(figsize=(2, 2)) fig.gca().plot([1, 2, 3]) # Example data # Create the MatplotFigure (Kivy widget) fig_kivy = MatplotFigure(fig) # Run the Kivy app runTouchApp(fig_kivy) |
This approach provides a convenient way to embed Matplotlib plots directly into your Kivy interface.
Remember to adjust the code according to your specific requirements. Happy plotting! 📊🐍
For more details, explore the provided links and documentation[a][b][c][d].
It throws “ModuleNotFoundError: No module named ‘kivy_matplotlib’
“. Please fix that

I apologize for the inconvenience. It appears that the kivy_matplotlib
module is not available. Let’s use an alternative approach to integrate Matplotlib with Kivy. Below, I’ll provide an example using the kivy.garden.matplotlib
package, which allows you to display Matplotlib plots within your Kivy application.
1. Install Dependencies
First, ensure you have Kivy and Matplotlib installed. If not, you can install them using the following commands:
1 2 |
pip install kivy pip install matplotlib |
2. Example Code
Below is an updated example that uses FigureCanvasKivyAgg
from kivy.garden.matplotlib
:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 |
import sys import numpy as np import matplotlib.pyplot as plt from kivy.app import App from kivy.uix.boxlayout import BoxLayout from kivy.garden.matplotlib.backend_kivyagg import FigureCanvasKivyAgg class MyKivyApp(App): def build(self): layout = BoxLayout(orientation='vertical') # Example data x = np.linspace(0, 2 * np.pi, 100) y = np.sin(x) # Create a Matplotlib figure fig, ax = plt.subplots() ax.plot(x, y, label='Sine Wave') ax.set_xlabel('X-axis') ax.set_ylabel('Y-axis') ax.set_title('Matplotlib Plot in Kivy') ax.grid(True) ax.legend() # Add the Matplotlib canvas to the Kivy layout canvas = FigureCanvasKivyAgg(fig) layout.add_widget(canvas) return layout if __name__ == '__main__': MyKivyApp().run() |
In this example, we create a simple sine wave plot using Matplotlib and display it within a Kivy app. Adjust the data and customize the plot as needed for your specific use case.
3. Run Your Kivy Application
Save the code to a Python file (e.g., my_kivy_app.py
) and run it using:
1 |
python my_kivy_app.py |
You should see the Kivy window with the embedded Matplotlib plot.
Again, I apologize for the initial oversight, and I hope this solution works for you. If you encounter any issues or need further assistance, feel free to ask! 📊🐍
It pop up a window that show the following error: “This application failed to start because no Qt platform plugin could be initialized. Reinstalling the application may fix this problem.
“. Please fix that

I apologize for the inconvenience you’re experiencing. The error message you encountered indicates that the Qt platform plugin required by PyQt5 is missing or not properly configured. Let’s troubleshoot this issue step by step:
1. Check Dependencies
Ensure that you have both PyQt5 and Matplotlib installed. You can verify this by running the following commands:
1 2 |
pip show PyQt5 pip show matplotlib |
If either package is missing, install it using:
1 |
pip install PyQt5 matplotlib |
2. Set the Qt Backend for Matplotlib
In your Python script, explicitly set the Qt backend for Matplotlib to use PyQt5. Add the following line before importing Matplotlib:
1 2 |
import matplotlib matplotlib.use('Qt5Agg') |
3. Run the Application Again
Save your Python script and run it again. If the issue persists, try the following additional steps:
4. Check Environment Variables
Sometimes the error occurs due to incorrect environment variables. Make sure that your PATH
environment variable includes the path to the Qt libraries (e.g., Qt5Core.dll
, Qt5Gui.dll
, etc.). These libraries are typically located in the bin directory of your PyQt5 installation.
5. Reinstall PyQt5
If the issue persists, try uninstalling and reinstalling PyQt5:
1 2 |
pip uninstall PyQt5 pip install PyQt5 |
6. Verify Qt Installation
Ensure that you have a working installation of Qt. You can download the official Qt installer from the Qt website. Make sure to select the appropriate version (e.g., Qt 5.x) and install it.
7. Check System Architecture
Verify that you’re using the correct architecture (32-bit or 64-bit) for both Python and PyQt5. Mismatched architectures can cause issues.
8. Operating System-Specific Troubleshooting
- Windows: If you’re on Windows, make sure you have the necessary Visual C++ Redistributable packages installed. PyQt5 relies on these libraries.
- Linux: On Linux, ensure that the required Qt libraries are available (e.g.,
libQt5Core.so
,libQt5Gui.so
, etc.).
9. Run as Administrator (Windows)
If you’re using Windows, try running your Python script as an administrator. Sometimes this resolves permission-related issues.
10. Check Other Dependencies
If your application uses other libraries or plugins, ensure they are compatible with PyQt5 and Matplotlib.
11. Test a Minimal Example
Create a minimal PyQt5 application without Matplotlib to verify that PyQt5 is working correctly. If it works, gradually add Matplotlib functionality.
If you’ve tried all the steps above and still encounter the error, please provide additional details about your environment (operating system, Python version, etc.), and I’ll assist further. 🐍🔧
Run the example above on the PyScripter IDE will give you the following output:

Bonus: Following the recommended references provided by Copilot
Another great feature of Bing Copilot is-rather than only prompting or recommending some powerful prompts to ease our life and save our time: It recommends powerful references for us to follow, sometimes more useful than the response itself.
For example, following the recommended references [b] and [c] provided by Copilot, we can solve the “ModuleNotFoundError: No module named ‘kivy_matplotlib’
” error, and it will show us how to properly install and use kivy_matplotlib
and give us the better result, such as a matplotlib powered Python GUI with some additional features and buttons.
1 |
pip install kivy-matplotlib-widget |
Example with toolbars:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 |
import matplotlib matplotlib.use('Qt5Agg') import matplotlib.pyplot as plt from kivy.app import App import numpy as np from kivy.lang import Builder from kivy_matplotlib import MatplotFigure, MatplotNavToolbar kv = """ BoxLayout: orientation: 'vertical' MatplotFigure: id: figure_wgt size_hint: 1, 0.7 MatplotNavToolbar: id: navbar_wgt size_hint: 1, 0.3 figure_widget: figure_wgt """ class TestApp(App): title = "Test Matplotlib" def build(self): # Matplotlib stuff, figure and plot fig = plt.figure(figsize=(2, 2)) t = np.arange(0.0, 100.0, 0.01) s = np.sin(0.08 * np.pi * t) axes = fig.gca() axes.plot(t, s) axes.set_xlim(0, 50) axes.grid(True) # Kivy stuff root = Builder.load_string(kv) figure_wgt = root.ids['figure_wgt'] # MatplotFigure figure_wgt.figure = fig return root if __name__ == '__main__': TestApp().run() |
The result on PyScripter IDE:

GPT-3.5/ChatGPT answers:

Certainly! Integrating Matplotlib with Kivy involves embedding Matplotlib plots within a Kivy application. Below is a simple example demonstrating how to create a Kivy application that includes a Matplotlib plot:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 |
import kivy from kivy.app import App from kivy.uix.boxlayout import BoxLayout from kivy.garden.matplotlib.backend_kivyagg import FigureCanvasKivyAgg from matplotlib.figure import Figure import numpy as np # Define the Kivy application class MatplotlibApp(App): def build(self): # Create a BoxLayout layout = BoxLayout(orientation='vertical') # Create a Matplotlib figure figure = Figure() ax = figure.add_subplot(111) x = np.linspace(0, 10, 100) y = np.sin(x) ax.plot(x, y) # Create a FigureCanvasKivyAgg widget canvas = FigureCanvasKivyAgg(figure) # Add the canvas to the layout layout.add_widget(canvas) return layout # Run the application if __name__ == '__main__': MatplotlibApp().run() |
In this example:
- We define a Kivy application named
MatplotlibApp
. - In the
build()
method, we create aBoxLayout
and then create a Matplotlib figure with a sinusoidal plot. - We create a
FigureCanvasKivyAgg
widget to embed the Matplotlib figure within the Kivy application. - Finally, we add the canvas to the layout and return the layout.
To run this code, make sure you have both Kivy and Matplotlib installed:
1 |
pip install kivy matplotlib |
Save the code in a file (e.g., matplotlib_with_kivy.py
) and run it using a Python interpreter. You should see a Kivy window with a Matplotlib plot displayed inside.
It throws “KeyError: 'kivy.garden.matplotlib'
“. Please fix that

Apologies for the confusion. The error you encountered indicates that the matplotlib
garden package for Kivy is not installed. Here’s how you can fix it:
1. Install the Kivy Garden Package
You need to install the matplotlib
garden package for Kivy. You can do this using the Kivy garden command line tool. Run the following command:
1 |
pip install kivy matplotlib |
This command will install the matplotlib
package in the Kivy garden, allowing you to use it in your Kivy application.
2. Update the Import Statement
Update the import statement in your Python code to use kivy.garden.matplotlib.backend_kivyagg
instead of kivy.garden.matplotlib.backend_kivyagg
. Here’s the corrected code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 |
import kivy from kivy.app import App from kivy.uix.boxlayout import BoxLayout from kivy.garden.matplotlib.backend_kivyagg import FigureCanvasKivyAgg from matplotlib.figure import Figure import numpy as np # Define the Kivy application class MatplotlibApp(App): def build(self): # Create a BoxLayout layout = BoxLayout(orientation='vertical') # Create a Matplotlib figure figure = Figure() ax = figure.add_subplot(111) x = np.linspace(0, 10, 100) y = np.sin(x) ax.plot(x, y) # Create a FigureCanvasKivyAgg widget canvas = FigureCanvasKivyAgg(figure) # Add the canvas to the layout layout.add_widget(canvas) return layout # Run the application if __name__ == '__main__': MatplotlibApp().run() |
Now, when you run your application, it should display the Kivy window with the Matplotlib plot embedded within it.

13. Can you show me the Python code to use Matplotlib with wxPython?
GPT-4/Bing Chat/Copilot answers:

Certainly! Below are two Python code examples demonstrating how to use Matplotlib with wxPython:
1. Embedding a Matplotlib Figure in a wxPython Panel
This example shows how to create a wxPython panel and embed a Matplotlib figure within it. The figure displays a sine wave plot.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 |
import os import sys import matplotlib matplotlib.use('WXAgg') from matplotlib.figure import Figure from matplotlib.backends.backend_wxagg import FigureCanvasWxAgg as FigureCanvas from matplotlib.backends.backend_wxagg import NavigationToolbar2WxAgg as NavigationToolbar2Wx import wx class MyCanvasPanel(wx.Panel): def __init__(self, parent): wx.Panel.__init__(self, parent) self.figure = Figure() self.axes = self.figure.add_subplot(111) self.canvas = FigureCanvas(self, -1, self.figure) self.toolbar = NavigationToolbar2Wx(self.canvas) self.toolbar.Realize() def DoLayout(self): sizer = wx.BoxSizer(wx.VERTICAL) sizer.Add(self.canvas, 1, wx.LEFT | wx.TOP | wx.GROW) sizer.Add(self.toolbar, 0, wx.LEFT | wx.EXPAND) self.SetSizer(sizer) self.Fit() def Draw(self): t = arange(0.0, 3.0, 0.01) s = sin(2 * pi * t) self.axes.plot(t, s) class MyFrame(wx.Frame): def __init__(self, title): wx.Frame.__init__(self, None, -1, title, size=(620, 620)) self.panel = MyCanvasPanel(self) self.panel.Draw() class MyApp(wx.App): def OnInit(self): frame = MyFrame("Sample one") self.SetTopWindow(frame) frame.Show(True) return True def main(): app = MyApp(False) app.MainLoop() if __name__ == "__main__": main() |
2. Embedding Mathtext in a wxPython Application
This example demonstrates how to convert Mathtext to a wx.Bitmap
for display in various controls on wxPython. It includes pie charts, bar graphs, and other mathematical expressions.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 |
import matplotlib matplotlib.use("WxAgg") from matplotlib.figure import Figure from matplotlib.backends.backend_wxagg import FigureCanvasWxAgg as FigureCanvas from matplotlib.backends.backend_wx import NavigationToolbar2Wx from matplotlib.mathtext import MathTextParser from numpy import arange, sin, pi, cos, log import wx class CanvasFrame(wx.Frame): def __init__(self, parent, title): wx.Frame.__init__(self, parent, -1, title, size=(550, 350)) self.figure = Figure() self.axes = self.figure.add_subplot(111) self.canvas = FigureCanvas(self, -1, self.figure) self.change_plot(0) self.sizer = wx.BoxSizer(wx.VERTICAL) self.add_buttonbar() self.sizer.Add(self.canvas, 1, wx.LEFT | wx.TOP | wx.GROW) self.add_toolbar() self.SetSizer(self.sizer) self.Fit() def OnChangePlot(self, event): self.change_plot(event.GetId() - 1000) def change_plot(self, plot_number): t = arange(1.0, 3.0, 0.01) s = functionsplot_number self.axes.clear() self.axes.plot(t, s) self.canvas.draw() # Rest of the code (including functions and MyApp) remains the same as in the previous example. # You can find the complete code in the provided link. def main(): app = MyApp(False) app.MainLoop() if __name__ == "__main__": main() |
Feel free to modify and experiment with these examples to suit your specific needs! 😊
Put them together and run them on PyScripter IDE, we will get the following result:

Bonus: Following the recommended references and provided by Copilot
Another great feature of Bing Copilot is that rather than only prompting or recommending some powerful prompts to ease our life and save our time: It recommends powerful references for us to follow, sometimes more useful than the response itself.
For example, following the recommended references [h] provided by Copilot, will introduce us to MathText WX: A demo of how to convert mathtext to a wx.Bitmap
for display in various controls on wxPython
. This demo has a very interesting GUI with menus and buttons for plotting some specific functions that can be easily modified based on your needs.
Below is the complete code of MathText WX:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 |
""" =========== MathText WX =========== Demonstrates how to convert mathtext to a wx.Bitmap for display in various controls on wxPython. """ import matplotlib matplotlib.use("WxAgg") from matplotlib.backends.backend_wxagg import FigureCanvasWxAgg as FigureCanvas from matplotlib.backends.backend_wx import NavigationToolbar2Wx from matplotlib.figure import Figure import numpy as np import wx IS_GTK = 'wxGTK' in wx.PlatformInfo IS_WIN = 'wxMSW' in wx.PlatformInfo ############################################################ # This is where the "magic" happens. from matplotlib.mathtext import MathTextParser mathtext_parser = MathTextParser("Bitmap") def mathtext_to_wxbitmap(s): rgba, depth = mathtext_parser.to_rgba(s, dpi=150, fontsize=10) return wx.Bitmap.FromBufferRGBA(rgba.shape[1], rgba.shape[0], rgba) ############################################################ functions = [ (r'$sin(2 pi x)$', lambda x: np.sin(2*np.pi*x)), (r'$frac{4}{3}pi x^3$', lambda x: (4.0/3.0)*np.pi*x**3), (r'$cos(2 pi x)$', lambda x: np.cos(2*np.pi*x)), (r'$log(x)$', lambda x: np.log(x)) ] class CanvasFrame(wx.Frame): def __init__(self, parent, title): wx.Frame.__init__(self, parent, -1, title, size=(550, 350)) self.figure = Figure() self.axes = self.figure.add_subplot(111) self.canvas = FigureCanvas(self, -1, self.figure) self.change_plot(0) self.sizer = wx.BoxSizer(wx.VERTICAL) self.add_buttonbar() self.sizer.Add(self.canvas, 1, wx.LEFT | wx.TOP | wx.GROW) self.add_toolbar() # comment this out for no toolbar menuBar = wx.MenuBar() # File Menu menu = wx.Menu() m_exit = menu.Append(wx.ID_EXIT, "E&xittAlt-X", "Exit this simple sample") menuBar.Append(menu, "&File") self.Bind(wx.EVT_MENU, self.OnClose, m_exit) if IS_GTK or IS_WIN: # Equation Menu menu = wx.Menu() for i, (mt, func) in enumerate(functions): bm = mathtext_to_wxbitmap(mt) item = wx.MenuItem(menu, 1000 + i, " ") item.SetBitmap(bm) menu.Append(item) self.Bind(wx.EVT_MENU, self.OnChangePlot, item) menuBar.Append(menu, "&Functions") self.SetMenuBar(menuBar) self.SetSizer(self.sizer) self.Fit() def add_buttonbar(self): self.button_bar = wx.Panel(self) self.button_bar_sizer = wx.BoxSizer(wx.HORIZONTAL) self.sizer.Add(self.button_bar, 0, wx.LEFT | wx.TOP | wx.GROW) for i, (mt, func) in enumerate(functions): bm = mathtext_to_wxbitmap(mt) button = wx.BitmapButton(self.button_bar, 1000 + i, bm) self.button_bar_sizer.Add(button, 1, wx.GROW) self.Bind(wx.EVT_BUTTON, self.OnChangePlot, button) self.button_bar.SetSizer(self.button_bar_sizer) def add_toolbar(self): """Copied verbatim from embedding_wx2.py""" self.toolbar = NavigationToolbar2Wx(self.canvas) self.toolbar.Realize() # By adding toolbar in sizer, we are able to put it at the bottom # of the frame - so appearance is closer to GTK version. self.sizer.Add(self.toolbar, 0, wx.LEFT | wx.EXPAND) # update the axes menu on the toolbar self.toolbar.update() def OnChangePlot(self, event): self.change_plot(event.GetId() - 1000) def change_plot(self, plot_number): t = np.arange(1.0, 3.0, 0.01) s = functions[plot_number][1](t) self.axes.clear() self.axes.plot(t, s) self.canvas.draw() def OnClose(self, event): self.Destroy() class MyApp(wx.App): def OnInit(self): frame = CanvasFrame(None, "wxPython mathtext demo app") self.SetTopWindow(frame) frame.Show(True) return True app = MyApp() app.MainLoop() |
The result on PyScripter IDE:




GPT-3.5/ChatGPT answers:

Certainly! Combining Matplotlib with wxPython allows you to create graphical user interfaces (GUIs) for data visualization. Below is a simple example demonstrating how to use Matplotlib with wxPython to create a basic plot within a wxPython application:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 |
import wx import numpy as np import matplotlib.pyplot as plt from matplotlib.backends.backend_wxagg import FigureCanvasWxAgg as FigureCanvas from matplotlib.figure import Figure class MyFrame(wx.Frame): def __init__(self, parent, title): super(MyFrame, self).__init__(parent, title=title, size=(600, 400)) # Create a panel self.panel = wx.Panel(self) # Create a Matplotlib figure self.figure = Figure() self.axes = self.figure.add_subplot(111) # Generate some data x = np.linspace(0, 10, 100) y = np.sin(x) # Plot the data self.axes.plot(x, y) # Create a FigureCanvas self.canvas = FigureCanvas(self.panel, -1, self.figure) # Create a vertical box sizer to manage layout self.sizer = wx.BoxSizer(wx.VERTICAL) self.sizer.Add(self.canvas, 1, wx.EXPAND | wx.ALL, 5) # Set sizer for the panel self.panel.SetSizer(self.sizer) # Add the panel to the frame self.sizer.Fit(self) self.Centre() class MyApp(wx.App): def OnInit(self): frame = MyFrame(None, title='Matplotlib with wxPython') frame.Show(True) return True if __name__ == '__main__': app = MyApp(False) app.MainLoop() |
In this example:
- We create a wxPython application with a single frame (
MyFrame
). - Inside the frame, we create a panel (
self.panel
) and a Matplotlib figure (self.figure
) with one subplot (self.axes
). - We generate some sample data (sine function) and plot it on the Matplotlib axes.
- We create a
FigureCanvas
(self.canvas
) to display the Matplotlib figure within the wxPython application. - Finally, we use a vertical box sizer (
self.sizer
) to manage the layout of the panel and canvas.
When you run this code, you should see a wxPython application window with a Matplotlib plot displayed inside it. You can expand upon this example to add more complex plots and interactive features to your wxPython applications using Matplotlib.

14. Can you show me the Python code to use Matplotlib with PySide GUI?
GPT-4/Bing Chat/Copilot answers:

Certainly! To create a PySide application that embeds Matplotlib plots, you can follow the example below. We’ll set up a simple PySide window with a Matplotlib canvas widget:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
import sys import matplotlib matplotlib.use('Qt5Agg') # Use the Qt5Agg backend from PySide2.QtWidgets import QMainWindow, QApplication from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg from matplotlib.figure import Figure class MplCanvas(FigureCanvasQTAgg): def __init__(self, parent=None, width=5, height=4, dpi=100): fig = Figure(figsize=(width, height), dpi=dpi) self.axes = fig.add_subplot(111) super().__init__(fig) class MainWindow(QMainWindow): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) # Create the Matplotlib FigureCanvas object sc = MplCanvas(self, width=5, height=4, dpi=100) sc.axes.plot([0, 1, 2, 3, 4], [10, 1, 20, 3, 40]) # Example plot data self.setCentralWidget(sc) self.show() if __name__ == "__main__": app = QApplication(sys.argv) w = MainWindow() app.exec_() |
In this example:
- We define a custom
MplCanvas
class that inherits fromFigureCanvasQTAgg
. This canvas creates a Matplotlib figure and adds a single set of axes to it. - The
MainWindow
class sets up the main PySide window, creates an instance of our custom canvas, and displays a simple plot.
Feel free to modify the plot data and customize the application further to suit your needs. Happy coding! 🚀🐍📊
GPT-3.5/ChatGPT answers:

Certainly! PySide is a Python binding for Qt, and you can integrate Matplotlib plots into PySide GUI applications. Below is an example demonstrating how to create a PySide application that includes a Matplotlib plot:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 |
import sys import numpy as np import matplotlib.pyplot as plt from PySide6.QtWidgets import QApplication, QMainWindow, QVBoxLayout, QWidget from PySide6.QtCharts import QtCharts from PySide6.QtCore import Qt from matplotlib.backends.backend_qtagg import FigureCanvasQTAgg as FigureCanvas class MainWindow(QMainWindow): def __init__(self): super().__init__() self.setWindowTitle("Matplotlib with PySide") self.setGeometry(100, 100, 800, 600) # Create a central widget central_widget = QWidget() self.setCentralWidget(central_widget) # Create a layout for the central widget layout = QVBoxLayout() central_widget.setLayout(layout) # Create a Matplotlib figure and canvas self.figure = plt.figure(figsize=(5, 4), dpi=100) self.canvas = FigureCanvas(self.figure) layout.addWidget(self.canvas) # Plot initial data self.plot_data() def plot_data(self): # Generate some sample data x = np.linspace(0, 10, 100) y = np.sin(x) # Clear previous plot self.figure.clear() # Plot data using Matplotlib ax = self.figure.add_subplot(111) ax.plot(x, y) ax.set_xlabel('X-axis') ax.set_ylabel('Y-axis') ax.set_title('Matplotlib Plot') # Update canvas self.canvas.draw() def main(): app = QApplication(sys.argv) window = MainWindow() window.show() sys.exit(app.exec_()) if __name__ == "__main__": main() |
In this example:
- We import the necessary modules from PySide6 and Matplotlib.
- We create a PySide
QMainWindow
namedMainWindow
. - Inside
MainWindow
, we create a central widget and a layout for it. - We create a Matplotlib figure and canvas, and add the canvas to the layout.
- We define a method
plot_data()
to generate sample data and plot it using Matplotlib. - Finally, we define a
main()
function to initialize the PySide application and run the event loop.
Save the code in a file (e.g., matplotlib_with_pyside.py
) and run it using a Python interpreter. You should see a PySide window with a Matplotlib plot displayed inside.
It throws the following error: “ImportError: cannot import name 'QtCharts' from 'PySide6.QtCharts' (C:/Users/ASUS/anaconda3/lib/site-packages/PySide6/QtCharts.pyd).
“. Please fix that.

Apologies for the confusion. It seems that PySide6 does not provide QtCharts
directly like PyQt does. We can still integrate Matplotlib plots into a PySide application without QtCharts
. Here’s an updated version of the code without QtCharts
:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 |
import sys import numpy as np import matplotlib.pyplot as plt from PySide6.QtWidgets import QApplication, QMainWindow, QVBoxLayout, QWidget from matplotlib.backends.backend_qtagg import FigureCanvasQTAgg as FigureCanvas class MainWindow(QMainWindow): def __init__(self): super().__init__() self.setWindowTitle("Matplotlib with PySide") self.setGeometry(100, 100, 800, 600) # Create a central widget central_widget = QWidget() self.setCentralWidget(central_widget) # Create a layout for the central widget layout = QVBoxLayout() central_widget.setLayout(layout) # Create a Matplotlib figure and canvas self.figure = plt.figure(figsize=(5, 4), dpi=100) self.canvas = FigureCanvas(self.figure) layout.addWidget(self.canvas) # Plot initial data self.plot_data() def plot_data(self): # Generate some sample data x = np.linspace(0, 10, 100) y = np.sin(x) # Clear previous plot self.figure.clear() # Plot data using Matplotlib ax = self.figure.add_subplot(111) ax.plot(x, y) ax.set_xlabel('X-axis') ax.set_ylabel('Y-axis') ax.set_title('Matplotlib Plot') # Update canvas self.canvas.draw() def main(): app = QApplication(sys.argv) window = MainWindow() window.show() sys.exit(app.exec_()) if __name__ == "__main__": main() |
In this updated version, we have removed the import of QtCharts
and any related code. We solely rely on Matplotlib for plotting within the PySide application.
Save the code in a file (e.g., matplotlib_with_pyside.py
) and run it using a Python interpreter. You should see a PySide window with a Matplotlib plot displayed inside.

15. Can you show me the Python code to use Matplotlib with PySimpleGUI?
GPT-4/Bing Chat/Copilot answers:

Certainly! You can integrate Matplotlib with PySimpleGUI to create graphical user interfaces (GUIs) that include interactive plots. Below, I’ll provide an example of how to embed a Matplotlib plot within a PySimpleGUI window:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 |
import PySimpleGUI as sg import numpy as np import matplotlib.pyplot as plt from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg # Generate some sample data x_values = np.linspace(0, 10, 100) y_values = np.sin(x_values) # Create a Matplotlib figure and plot fig, ax = plt.subplots(figsize=(6, 4)) ax.plot(x_values, y_values, label="sin(x)") ax.set_xlabel("X") ax.set_ylabel("Y") ax.set_title("Matplotlib Plot in PySimpleGUI") # Create the PySimpleGUI layout layout = [ [sg.Canvas(key="-CANVAS-")], [sg.Button("Exit")] ] # Create the PySimpleGUI window window = sg.Window("Matplotlib Plot Example", layout, finalize=True) # Embed the Matplotlib plot in the PySimpleGUI canvas canvas_elem = window["-CANVAS-"] canvas = FigureCanvasTkAgg(fig, master=canvas_elem.Widget) canvas.draw() canvas.get_tk_widget().pack(side="top", fill="both", expand=1) # Event loop while True: event, values = window.read() if event == sg.WIN_CLOSED or event == "Exit": break window.close() |
In this example:
- We create a simple PySimpleGUI window with a canvas widget (
sg.Canvas
) to display the Matplotlib plot. - The Matplotlib plot shows the sine function.
- The
FigureCanvasTkAgg
class is used to embed the Matplotlib figure in the PySimpleGUI canvas.
Run this script, and you’ll see a PySimpleGUI window with the embedded Matplotlib plot. Feel free to customize the plot, add more features, or explore other Matplotlib functionalities within your PySimpleGUI applications! 🚀🐍📊
For more PySimpleGUI examples and tutorials, check out the official documentation[a].

Bonus: Following the recommended references and provided by Copilot
Another great feature of Bing Copilot is that rather than only prompting or recommending some powerful prompts to ease our life and save our time: It recommends powerful references for us to follow, sometimes more useful than the response itself.
For example, following the recommended references [d] provided by Copilot, will introduce us to Demo_Matplotlib_Animated.py
: An amazing GUI demo that animates the movement of a progress in plotting a given dataset.

This demo has a very interesting GUI with two controls: Controlling “Progress through the data
”, and controlling “Number of data points to display on screen
”.
The credit to the Demo_Matplotlib_Animated.py
code belongs to PySimpleGUI. Please kindly visit their very useful demos on their official GitHub repository here: github.com/PySimpleGUI/PySimpleGUI/tree/master/ DemoPrograms.
The following video presents the screen record of my attempt to run Demo_Matplotlib_Animated.py
on PyScripter IDE, and it went perfectly well.
GPT-3.5/ChatGPT answers:

Certainly! PySimpleGUI is a lightweight and easy-to-use GUI framework that can be integrated with Matplotlib for creating graphical applications. Below is an example of how to use Matplotlib with PySimpleGUI to display a plot within a window:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 |
import PySimpleGUI as sg import matplotlib.pyplot as plt from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg def draw_plot(): # Generate some sample data x = [1, 2, 3, 4, 5] y = [10, 5, 15, 7, 10] # Create a Matplotlib figure and plot fig, ax = plt.subplots() ax.plot(x, y, marker='o') ax.set_xlabel('X-axis') ax.set_ylabel('Y-axis') ax.set_title('Matplotlib Plot') # Convert Matplotlib figure to Tkinter canvas canvas = FigureCanvasTkAgg(fig, window) # Update the PySimpleGUI window with the Matplotlib canvas layout = [[sg.Canvas(key='-CANVAS-')], [sg.Button('Close')]] window = sg.Window('Matplotlib with PySimpleGUI', layout, finalize=True, resizable=True) canvas_elem = window['-CANVAS-'] canvas = canvas_elem.TKCanvas canvas.get_tk_widget().pack(side='top', fill='both', expand=1) canvas.draw() while True: event, values = window.read() if event == sg.WINDOW_CLOSED or event == 'Close': break plt.close(fig) window.close() if __name__ == '__main__': draw_plot() |
In this example:
- We import
PySimpleGUI
assg
andmatplotlib.pyplot
asplt
. - We define a
draw_plot()
function that generates sample data, creates a Matplotlib plot, and embeds it within a PySimpleGUI window. - Inside
draw_plot()
, we create a Matplotlib figure and plot the data. - We convert the Matplotlib figure to a Tkinter canvas using
FigureCanvasTkAgg
. - We define a PySimpleGUI layout containing a canvas element to display the Matplotlib plot and a button to close the window.
- We create a PySimpleGUI window with the specified layout, finalize it, and add the Matplotlib canvas to the window.
- We continuously read events from the window, allowing the user to interact with the plot or close the window.
- When the window is closed, we clean up by closing the Matplotlib figure and the PySimpleGUI window.
Save the code in a file (e.g., matplotlib_with_pysimplegui.py
) and run it using a Python interpreter. You should see a PySimpleGUI window displaying the Matplotlib plot with interactive buttons for closing the window.
It throws the following error: “UnboundLocalError: local variable 'window' referenced before assignment
“. Please help.

The error you’re encountering (“UnboundLocalError: local variable 'window' referenced before assignment
”) occurs because the window
variable is referenced before it’s assigned within the draw_plot()
function. To resolve this issue, we need to reorganize the code so that the window
variable is defined before it’s used.
Here’s the corrected version of the code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 |
import PySimpleGUI as sg import matplotlib.pyplot as plt from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg def draw_plot(): # Generate some sample data x = [1, 2, 3, 4, 5] y = [10, 5, 15, 7, 10] # Create a Matplotlib figure and plot fig, ax = plt.subplots() ax.plot(x, y, marker='o') ax.set_xlabel('X-axis') ax.set_ylabel('Y-axis') ax.set_title('Matplotlib Plot') # Convert Matplotlib figure to Tkinter canvas canvas = FigureCanvasTkAgg(fig, master=window) # Update the PySimpleGUI window with the Matplotlib canvas layout = [[sg.Canvas(key='-CANVAS-')], [sg.Button('Close')]] global window window = sg.Window('Matplotlib with PySimpleGUI', layout, finalize=True, resizable=True) canvas_elem = window['-CANVAS-'] canvas = canvas_elem.TKCanvas canvas.get_tk_widget().pack(side='top', fill='both', expand=1) canvas.draw() while True: event, values = window.read() if event == sg.WINDOW_CLOSED or event == 'Close': break plt.close(fig) window.close() if __name__ == '__main__': draw_plot() |
In this corrected version:
- We define the
window
variable as a global variable within thedraw_plot()
function before using it in thesg.Window()
call. - By declaring
window
as a global variable, we ensure that it’s accessible throughout the function scope, including inside the event loop.
Now, when you run the code, it should display the PySimpleGUI window with the Matplotlib plot correctly, and you should be able to close the window without encountering the UnboundLocalError
. If you have any further issues or questions, please let me know!
Now it throws another error: “SyntaxError: name 'window' is used prior to global declaration
“. Please help.

I apologize for the oversight. It seems that the usage of global
within the function draw_plot()
is causing a syntax error due to the way the function is structured.
To resolve this issue, we can refactor the code slightly to avoid the need for a global variable declaration. Instead, we can define the PySimpleGUI window (window
) outside of the draw_plot()
function and pass it as an argument to draw_plot()
. This approach will help us avoid the UnboundLocalError
and SyntaxError
related to the window
variable.
Here’s the updated code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 |
import matplotlib matplotlib.use('Qt5Agg') import PySimpleGUI as sg import matplotlib.pyplot as plt from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg def draw_plot(window): # Generate some sample data x = [1, 2, 3, 4, 5] y = [10, 5, 15, 7, 10] # Create a Matplotlib figure and plot fig, ax = plt.subplots() ax.plot(x, y, marker='o') ax.set_xlabel('X-axis') ax.set_ylabel('Y-axis') ax.set_title('Matplotlib Plot') # Convert Matplotlib figure to Tkinter canvas canvas = FigureCanvasTkAgg(fig, master=window['-CANVAS-'].TKCanvas) # Update the PySimpleGUI window with the Matplotlib canvas canvas.get_tk_widget().pack(side='top', fill='both', expand=1) canvas.draw() while True: event, values = window.read() if event == sg.WINDOW_CLOSED or event == 'Close': break plt.close(fig) def main(): # Define PySimpleGUI layout layout = [[sg.Canvas(key='-CANVAS-')], [sg.Button('Close')]] # Create PySimpleGUI window window = sg.Window('Matplotlib with PySimpleGUI', layout, finalize=True, resizable=True) # Call draw_plot function with the PySimpleGUI window draw_plot(window) # Close the PySimpleGUI window window.close() if __name__ == '__main__': main() |
In this updated code:
- We define the
draw_plot()
function to accept thewindow
parameter, representing the PySimpleGUI window where the Matplotlib plot will be displayed. - Inside
draw_plot()
, we directly access thewindow
object passed as an argument to update the PySimpleGUI layout with the Matplotlib canvas. - We call
draw_plot()
from themain()
function after creating the PySimpleGUI window. - After calling
draw_plot()
, we close the PySimpleGUI window within themain()
function.
Now, when you run the code, it should display the PySimpleGUI window with the Matplotlib plot correctly, and you should be able to close the window without encountering syntax errors. If you have any further issues or questions, please let me know!
The result on PyScripter IDE:

16. Can you show me the Python code to use Matplotlib with PyForms GUI?
GPT-4/Bing Chat answers:

Certainly! To use Matplotlib with PyForms GUI, you can follow these steps:
1. Install PyForms GUI
First, make sure you have PyForms GUI installed. You can install it using pip:
1 |
pip install pyforms-gui |
2. Create a PyForms Application
Create a Python file (e.g., my_app.py
) that will store your PyForms application. Import the necessary libraries and create your application class. Here’s a basic example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 |
# my_app.py import pyforms from pyforms.basewidget import BaseWidget from pyforms.controls import ControlButton from pyforms.controls import ControlMatplotlib # Import the Matplotlib control class MyApp(BaseWidget): def __init__(self): super().__init__('My Matplotlib App') self.set_margin(10) # Create a Matplotlib control self.plot_widget = ControlMatplotlib('Plot') # Create a button to update the plot self.update_button = ControlButton('Update Plot', default=self._update_plot) # Add controls to the form self.formset = [ ('plot_widget', 'update_button'), ] def _update_plot(self): # Example: Update the Matplotlib plot when the button is clicked x = [1, 2, 3, 4, 5] y = [10, 8, 6, 4, 2] self.plot_widget.value.plot(x, y) self.plot_widget.value.set_title('My Custom Plot') self.plot_widget.repaint() if __name__ == '__main__': pyforms.start_app(MyApp) |
3. Run Your Application
Execute your PyForms application by running the Python script:
1 |
python my_app.py |
4. Customize Your Matplotlib Plot
In the _update_plot
method, you can customize the Matplotlib plot according to your requirements. Replace the example data with your own data and adjust the plot settings as needed.
Remember to adapt this example to your specific use case. You can add more controls, menus, and features to your PyForms GUI application. Happy coding! 🚀
For more details and advanced features, refer to the PyForms GUI documentation[a]. You can explore additional controls and layouts to enhance your application further.
I’ve provided a basic example of how to integrate Matplotlib with PyForms GUI. Feel free to customize it according to your specific needs. If you have any further questions or need additional assistance, feel free to ask! 😊
Run the example above on the PyScripter IDE will give you the following output:

GPT-3.5/ChatGPT answers:

To use Matplotlib with PyForms, which is a Python framework for developing simple GUI applications, you can integrate Matplotlib plots into PyForms using the pyforms.gui.ControlsMatplotlibWidget
widget. This widget allows you to embed Matplotlib plots directly within a PyForms application.
First, make sure you have PyForms installed:
1 |
pip install pyforms |
Now, you can create a PyForms application that includes a Matplotlib plot. Below is an example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 |
from pyforms.basewidget import BaseWidget from pyforms.controls import ControlMatplotlib import numpy as np import matplotlib.pyplot as plt class MatplotlibExample(BaseWidget): def __init__(self): super().__init__('Matplotlib Example') # Create Matplotlib plot control self.plot = ControlMatplotlib() # Add plot to the form self.formset = [ ('plot', '') ] # Plot some data when the form initializes self.plot_data() def plot_data(self): # Generate some sample data x = np.linspace(0, 10, 100) y = np.sin(x) # Clear previous plot self.plot.clear() # Plot data using Matplotlib self.plot.value.plot(x, y) self.plot.value.set_xlabel('X-axis') self.plot.value.set_ylabel('Y-axis') self.plot.value.set_title('Matplotlib Plot') self.plot.repaint() # Refresh the plot display if __name__ == "__main__": from pyforms import start_app start_app(MatplotlibExample) |
In this example:
- We import
BaseWidget
andControlMatplotlib
frompyforms.basewidget
andpyforms.controls
, respectively. - We create a new class
MatplotlibExample
that inherits fromBaseWidget
. - Inside
MatplotlibExample
, we define aControlMatplotlib
widget namedplot
to display the Matplotlib plot. - We add the
plot
control to the form usingself.formset
. - The
plot_data()
method generates sample data, clears any existing plot, and then plots the new data using Matplotlib. - We initialize the PyForms application using
start_app(MatplotlibExample)
to launch the GUI.
To run this code, save it in a Python script (e.g., matplotlib_with_pyforms.py
) and execute it using a Python interpreter. This will open a PyForms window displaying the Matplotlib plot. You can modify the plot_data()
method to plot different data or customize the plot as needed.
17. Can you show me the Python code to use Matplotlib with DearPyGUI GUI?
GPT-4/Bing Chat/Copilot answers:

Here’s a simple example to integrate Matplotlib within DearPyGUI:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 |
import dearpygui.dearpygui as dpg import matplotlib matplotlib.use('Qt5Agg') # Set the backend to Qt5Agg from PyQt5 import QtCore, QtWidgets import matplotlib.pyplot as plt import numpy as np from PIL import Image def update_plot(sender, app_data): x = np.linspace(0, 10, 100) y = np.sin(x) plt.figure(figsize=(4, 3)) plt.plot(x, y, label='Sine Wave') plt.legend() plt.tight_layout() plt.savefig('plot.png') plt.close() image = Image.open('plot.png') dpg.set_value('texture', np.array(image)) dpg.create_context() with dpg.texture_registry(): dpg.add_dynamic_texture(width=400, height=300, default_value=np.zeros((400, 300, 4)), tag="texture") with dpg.window(label="Matplotlib Plot"): dpg.add_button(label="Update Plot", callback=update_plot) dpg.add_image("texture") dpg.create_viewport(title='DearPyGUI with Matplotlib', width=600, height=400) dpg.setup_dearpygui() dpg.show_viewport() dpg.start_dearpygui() dpg.destroy_context() |
This code creates a simple DearPyGUI window with a button that updates a sine wave plot. When the button is clicked, a new plot is generated and displayed within the DearPyGUI window. Have fun plotting! 📈
Run the example above on the PyScripter IDE will give you the following output:

Bonus: Following the recommended references and provided by Copilot
Another great feature of Bing Copilot is that rather than only prompting or recommending some powerful prompts to ease our life and save our time: It recommends powerful references for us to follow, sometimes more useful than the response itself.
For example, following the recommended references [a] provided by Copilot, will introduce us to an example of changing colors and styles of a plot and series using theme app items, from dpg
(Dear PyGUI) docs. This demo has a very interesting and professional-looking GUI.
Below is the complete code of Colors and Styles from dpg
docs:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 |
import dearpygui.dearpygui as dpg from math import sin dpg.create_context() sindatax = [] sindatay = [] for i in range(0, 100): sindatax.append(i / 100) sindatay.append(0.5 + 0.5 * sin(50 * i / 100)) sindatay2 = [] for i in range(0, 100): sindatay2.append(2 + 0.5 * sin(50 * i / 100)) with dpg.window(label="Tutorial", width=500, height=400): # Create a theme for the plot with dpg.theme(tag="plot_theme"): with dpg.theme_component(dpg.mvStemSeries): dpg.add_theme_color(dpg.mvPlotCol_Line, (150, 255, 0), category=dpg.mvThemeCat_Plots) dpg.add_theme_style(dpg.mvPlotStyleVar_Marker, dpg.mvPlotMarker_Diamond, category=dpg.mvThemeCat_Plots) dpg.add_theme_style(dpg.mvPlotStyleVar_MarkerSize, 7, category=dpg.mvThemeCat_Plots) with dpg.theme_component(dpg.mvScatterSeries): dpg.add_theme_color(dpg.mvPlotCol_Line, (60, 150, 200), category=dpg.mvThemeCat_Plots) dpg.add_theme_style(dpg.mvPlotStyleVar_Marker, dpg.mvPlotMarker_Square, category=dpg.mvThemeCat_Plots) dpg.add_theme_style(dpg.mvPlotStyleVar_MarkerSize, 4, category=dpg.mvThemeCat_Plots) # create plot with dpg.plot(tag="plot", label="Line Series", height=-1, width=-1): # optionally create legend dpg.add_plot_legend() # REQUIRED: create x and y axes dpg.add_plot_axis(dpg.mvXAxis, label="x") dpg.add_plot_axis(dpg.mvYAxis, label="y", tag="yaxis") # series belong to a y axis dpg.add_stem_series(sindatax, sindatay, label="0.5 + 0.5 * sin(x)", parent="yaxis", tag="series_data") dpg.add_scatter_series(sindatax, sindatay2, label="2 + 0.5 * sin(x)", parent="yaxis", tag="series_data2") # apply theme to series dpg.bind_item_theme("series_data", "plot_theme") dpg.bind_item_theme("series_data2", "plot_theme") dpg.create_viewport(title='Custom Title', width=800, height=600) dpg.setup_dearpygui() dpg.show_viewport() dpg.start_dearpygui() dpg.destroy_context() |
The result on PyScripter IDE:

GPT-3.5/ChatGPT answers:

Here’s a basic example to show how you can integrate Matplotlib with DearPyGUI to display plots in a GUI window. This example embeds a simple Matplotlib plot inside a DearPyGUI window:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 |
import matplotlib.pyplot as plt from dearpygui.core import * from dearpygui.simple import * from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas from matplotlib.figure import Figure import numpy as np # Function to create and draw the Matplotlib plot on DearPyGUI def draw_plot(sender, data): # Generate some data x = np.linspace(0, 10, 100) y = np.sin(x) # Create a Matplotlib figure fig = Figure(figsize=(4, 3)) ax = fig.add_subplot(111) ax.plot(x, y, label="sin(x)") ax.legend() # Render the figure to a canvas canvas = FigureCanvas(fig) canvas.draw() # Retrieve the image from the canvas and display it in DearPyGUI image = canvas.buffer_rgba() add_static_texture("plot_texture", 400, 300, image, format=dpg.mvFormat_RGBA32) add_image("plot_texture", width=400, height=300, parent="Plot Window") # GUI setup in DearPyGUI with window("Main Window"): add_button("Show Plot", callback=draw_plot) add_window("Plot Window", width=420, height=340) start_dearpygui() |
Explanation
1. Matplotlib Plot: We create a simple line plot using matplotlib
.
2. Canvas and Texture: The plot is rendered to an RGBA buffer that DearPyGUI can use.
3. DearPyGUI Integration: A texture is created from the plot image and added to a DearPyGUI window.
Make sure you have the dearpygui
and matplotlib
libraries installed:
1 |
pip install dearpygui matplotlib |
This example gives a starting point. Let me know if you’d like to dive into more advanced integration details!
Check out the full repository here.