user668074
user668074

Reputation: 1131

How do you create a Matplotlib widget in Kivy kv file?

I want to use a .kv file to make a Matplotlib widget, but I'm not sure how to do this.

Without a .kv file, the basic code looks like this:

from kivy.garden.matplotlib.backend_kivyagg import FigureCanvasKivyAgg
from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
import matplotlib.pyplot as plt

plt.plot([1, 23, 2, 4])
plt.ylabel('some numbers')

class MyApp(App):

    def build(self):
        box = BoxLayout()
        box.add_widget(FigureCanvasKivyAgg(plt.gcf()))
        return box

MyApp().run()

How is this done with a .kv file?

Upvotes: 1

Views: 3730

Answers (2)

badams
badams

Reputation: 108

You (and I) need to extend FigureCanvasKivyAgg as in John Anderson's answer to Python to KV Lang - FigureCanvasKivyAgg:

#!/usr/bin/env python3
from kivy.garden.matplotlib.backend_kivyagg import FigureCanvasKivyAgg
from kivy.app import App
import matplotlib.pyplot as plt

plt.plot([1, 23, 2, 4])
plt.ylabel('some numbers')

class MyFigure(FigureCanvasKivyAgg):
    def __init__(self, **kwargs):
        super().__init__(plt.gcf(), **kwargs)

class MyApp(App):
    pass

MyApp().run()

The kv file for the above question:

BoxLayout:
    MyFigure:

This fix also enabled me to set the position of the figure:

FloatLayout:
    MyFigure:
        pos: (400, 20)
        size: (300, 200)
        size_hint: (None, None)

Upvotes: 0

DrewTNBD
DrewTNBD

Reputation: 41

So here's what I figured out. In the .KV language file you specify a layout and give it an id:

BoxLayout:
    id: destination

Then in your python code you use the following:

self.ids.destination.add_widget(FigureCanvasKivyAgg(plt.gcf()))

So effectively you're using the id you setup in the kivy language file as a reference for your matplotlib graph.

Upvotes: 3

Related Questions