Search code examples
pythonflet

How to Display Matplotlib Heatmap in Flet Library?


I'm working on developing a data visualization application using the Flet framework. Within my application, I have a specific requirement to display a heatmap generated using Matplotlib. Unfortunately, I've encountered some difficulties when attempting to seamlessly integrate Matplotlib with the Flet library.

Here's a condensed version of the code I'm working with:

    

import matplotlib.pyplot as plt
import numpy as np

# Generate sample data
data = np.random.rand(10, 10)

# Create a heatmap`your text`
plt.imshow(data, cmap='hot', interpolation='nearest')
plt.colorbar()  # Add a colorbar

# Set axis labels
plt.xlabel('X-axis')
plt.ylabel('Y-axis')

# Set the title`your text`
plt.title('Example of a heatmap')

# Display the plot
plt.show()

I would greatly appreciate it if someone could provide guidance on how to properly display this Matplotlib heatmap within the context of the Flet library. Any assistance or examples demonstrating the integration of Matplotlib with Flet would be highly valuable. Thank you in advance!


Solution

  • I have also recently learned about Flet and have been doing a lot of research and creating tools. I adapted your code based on the matplotlib example in the reference, and rewrote matplotlib in OOP style to use fig.

    import matplotlib
    import matplotlib.pyplot as plt
    
    import flet as ft
    from flet.matplotlib_chart import MatplotlibChart
    
    matplotlib.use("svg")
    
    
    def main(page: ft.Page):
    
       # Generate sample data
        data = np.random.rand(10, 10)
    
        fig, ax = plt.subplots()
        # Create a heatmap`your text`
        im = ax.imshow(data, cmap='hot', interpolation='nearest')
        fig.colorbar(im)  # Add a colorbar
    
        # Set axis labels
        ax.set_xlabel('X-axis')
        ax.set_ylabel('Y-axis')
    
        # Set the title`your text`
        ax.set_title('Example of a heatmap')
    
        # Display the plot
        #plt.show()
        page.add(MatplotlibChart(fig, expand=True))
    
    
    ft.app(target=main)
    

    enter image description here