How to add Matplotlib graph in Kivy?


Integrating or adding matplotlib graphs into kivy applications can help developers to create more informative and engaging user interfaces. Kivy is an open-source Python framework that is used to develop mobile and dektop applications whereas Matplotlib is a data visualization library used for creating charts, graphs, and other visualizations. In this article, we will explore the steps involved in adding Matplotlib graphs in Kivy.

How to add a Matplotlib graph in Kivy?

Given below are the steps that we will follow to add a Matplotlib graph in Kivy −

Step 1

Create a virtual environment. You can name your virtual environment by anything you want in this article we will name it as kivy_venv. Use the below code to create a virtual environment −

Below is the code to make sure you have updated pip, wheel and virtualenv −

python -m pip install --upgrade pip wheel setuptools virtualenv

In your current directory, create a virtual environment named kivy_venv.

python -m virtualenv kivy_venv

Virtual environment activation.

kivy_venv\Scripts\activate

Step 2

Install matplotlib, kivy and kivy_garden −

Before we start integrating or adding Matplotlib graphs in Kivy, we need to install the required libraries. We can install Matplotlib, kivy, and other dependencies using pip. To install matplotlib use the command given below in the command prompt for Windows −

If the above code gives an error, then try then code given below:

pip install --upgrade matplotib
pip install matplotib

To install Kivy use the command given below in the terminal for Windows −

pip install kivy

To install kivy_garden use the command given below in the terminal for Windows −

pip install kivy_garden

To install dependencies and other modules for Kivy please refer to the installation guide for Kivy: here

For this article, we have used sublime text as the text editor and command prompt to run the Python files.

Step 3

Open the sublime text editor and add a new file, save the file as file_name.py the file should be of .py extension.

Now, let's create a Kivy app. Open your favorite text editor and create a new file called "mappy.py". This file will define the Kivy app and its user interface. Here is the code for the basic Kivy app −

Now next step is to create a kivy app. For this open your favorite text editor in this article we will be using Sublime text editor and create a new file called “main.py”, make sure that the file should be of .py extension but the filename could be anything you want. In this particular file, we will define the Kivy app and its user interface. Below is the code for the basic kivy app −

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 MainApp(MDApp):
   def build(self):
      self.theme_cls.theme_style = "Dark"
      self.theme_cls.primary_palette="BlueGray"
		
MainApp().run()

In the above code, we have imported the required kivy modules, defined the “MyApp” class which inherits from the “App” class, and defined the “build” method which returns a BoxLayout.

Step 4

In this step, we will add Matplot to kivy.

We will add Matplotlib to the kivy app. To do this, we need to create a Matplotlib figure and add it to the kivy app’s user interface. Below is the code to add a matplotlib figure to the kivy app.

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

#define what we want to graph
x=[11,22,33,44,55,66,77,88,99,100]
y=[12,6,9,15,23,67,11,90,34,91]

plt.plot(x,y)
plt.ylabel("Y axis")
plt.xlabel("X axis")
class MainApp(MDApp):
   def build(self):
      self.theme_cls.theme_style = "Dark"
      self.theme_cls.primary_palette="BlueGray"
		
MainApp().run()

In the above code, we have imported Matplotlib’s pyplot module and created a figure and axis. We also imported the FigureCanvas widget from the "kivy.garden.matplotlib.backend_kivyagg" module. This widget allows us to add the Matplotlib figure to the Kivy app’s user interface. Finally, we created a BoxLayout and added the FigureCanvas widget to it.

Step 5

In the next step, we will customize and design our App and matplotlib graph by creating a design file that has .kv extension . Create a new file and name the file "mappy.kv". below is the code to do the same −

<Matty>
   BoxLayout:
      id:box
      size_hint_y: .8
      pos_hint: {"top":1}
   BoxLayout:
      size_hint_y: .2
      TextInput:
         id:namer
         multiline: False
      Button:
         text: "Save It....."
         on_release: root.saveit()

Below is the code for both the files “mappy.py” and “mappy.kv”.

Program(“mappy.py” file)

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

#define what we want to graph
x=[11,22,33,44,55,66,77,88,99,100]
y=[12,6,9,15,23,67,11,90,34,91]

plt.plot(x,y)
plt.ylabel("Y axis")
plt.xlabel("X axis")

#Build our app

class Matty(FloatLayout):
   def __init__(self,**kwargs):
      super().__init__(**kwargs)

      box=self.ids.box
      box.add_widget(FigureCanvasKivyAgg(plt.gcf()))
   

   def save_it(self):
      pass

class MainApp(MDApp):
   def build(self):
      self.theme_cls.theme_style = "Dark"
      self.theme_cls.primary_palette="BlueGray"
      Builder.load_file('matty.kv')
      return Matty()

MainApp().run()

Program (“mappy.kv” file)

<Matty>
   BoxLayout:
      id:box
      size_hint_y: .8
      pos_hint: {"top":1}
   BoxLayout:
      size_hint_y: .2
      TextInput:
         id:namer
         multiline: False
      Button:
         text: "Save It....."
         on_release: root.saveit()

Open the command prompt and go to the directory where the “mappy.py” file is saved. Enter the below command in the command prompt.

python mappy.py

Here kivy_venv is the virtual environment.

Output

Conclusion

In conclusion, Integrating or adding matplotlib graphs into Kivy applications can help developers to create a more informative and engaging user interface. In this article, we have learned how to add Matplotlib graphs in Kivy. We have also seen how to customize the Matplotlib graph and design using the design file. By following the steps outlined in this article, developers can easily integrate Matplotlib graphs into their Kivy applications and create a more visually appealing user interface.

Updated on: 31-May-2023

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements