Reputation: 10110
I am just learning to use Kivy and want to embed some plots from Matplotlib and potentially OpenGL graphics in an app. I was looking at this particular tutorial on how to use kivy-garden to display a Matplotlib plot
However, I was hoping someone might be able to point me to an example of importing a plot into Kivy without using the matplotlib kivy-garden widgets. I want to be a little plotting backend agnostic, and hence I wanted to learn to import plots directly into the Kivy widgets. Matplotlib will export an image from plt.show()
so I imagine the corresponding Kivy widget needs to have a property that can receive images? Plotly exports something different, so I was hoping to understand how to directly import these different plots into Kivy.
If anyone knows some good examples of directly plotting into Kivy, it would be appreciated.
Upvotes: 1
Views: 488
Reputation: 627
You can load an Image. Here is an example hacked out of some code that I use.
kivy file:
#:kivy 2.0.0
<MatPlot>:
Image:
size_hint_x: 12
source: root.matplotlib_image2.source
Image:
size_hint_x: 5
source: root.matplotlib_image1.source
Python: my method on_start() probably needs to be called from some other code. I think the on_start is only intrinsic with App and not other widgets. I have used this with matplotlib which as you point out can export image files.
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
from pathlib import Path
from kivy.uix.image import Image
from kivy.uix.boxlayout import BoxLayout
# requires kivy element <MatPlot> from kv_mat_plot.kv
class MatPlot(BoxLayout):
matplotlib_image1 = Image()
matplotlib_image2 = Image()
def __init__(self,
graph_directory: Path,
**kwargs,
):
super().__init__(**kwargs)
self.graph_directory = graph_directory
def load_image1(self, filename: str):
self.matplotlib_image1.source = str(Path(self.graph_directory, filename))
self.matplotlib_image1.reload()
def load_image2(self, filename: str):
self.matplotlib_image2.source = str(Path(self.graph_directory, filename))
self.matplotlib_image2.reload()
def reload_image2(self):
self.matplotlib_image2.reload()
print(f"imag2={self.matplotlib_image2.source}")
def reload_image1(self):
self.matplotlib_image1.reload()
print(f"image1={self.matplotlib_image1.source}")
def reload_images(self):
self.reload_image2()
self.reload_image1()
def on_start(self):
print(f"{self.name} on_start {self}")
self.matplotlib_image2.source = str(Path(self.graph_directory, "one_image.png"))
self.matplotlib_image1.source = str(Path(self.graph_directory, "second_image.png"))
Upvotes: 2