简体   繁体   中英

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?

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.

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM