Skip to content Skip to sidebar Skip to footer

Add A Matplotlib Graph To A Widget In Kivymd

I am currently creating a mobile app with KivyMD which serves for managing travel expense requests. The user will enter a desired requested amount for different types of expenses o

Solution 1:

I think you just need to rebuild the plot with each change. Try changing your update_donut_graph() to:

def update_donut_graph(self):
    plt.clf()  # clear the plot
    travel_manager = MDApp.get_running_app().root.get_screen('travelManager')
    travel_manager.ids.expense_graph.clear_widgets()
    # create data
    names = 'Alimentación', 'Casetas', 'Gasolina',
    data_values = [MyContentAliment.monto_alimento, MyContentCasetas.monto_casetas,
               MyContentGasolina.monto_gasolina]

    # Create a white circle for the center of the plot
    my_circle = plt.Circle((0, 0), 0.65, color='white')
    # Create graph, add and place percentage labels# Add spaces to separate elements from the donut
    explode = (0.05, 0.05, 0.05)
    plt.pie(data_values, autopct="%.1f%%", startangle=0, pctdistance=0.80, labeldistance=1.2, explode=explode)

    p = plt.gcf()
    p.gca().add_artist(my_circle)
    # Create and place legend of the graph
    plt.legend(labels=names, loc="center")
    # Add graph to Kivy App# plt.show()# THE DESIRED RESULT IS TO ADD THE GRAPH TO THE APP WITH THE LINE OF CODE BELOW, INSTEAD OF THE plt.show() line
    travel_manager.ids.expense_graph.add_widget(FigureCanvasKivyAgg(figure=plt.gcf()))

Solution 2:

Thanks for your reply @John Anderson . As always, you've been of great help. I encounter however a simple problem. The size of my graph is modified, it is considerably smaller, yet the size of the legend remains the same. So instead of showing the graph how I desire, the legend now covers up the graph.

enter image description here

Is there a way I can prevent this? I've been thinking maybe a way to make the graph to take up the entire canvas size will be appropiate. As you can see in donut_graph_image.png screenshot, there is a lot of whitespace around the graph. Or a command that will help me maintain the sizes of the graph? I tried with Axes.set_aspect but this did worked.

Thanks again.

enter image description here

Post a Comment for "Add A Matplotlib Graph To A Widget In Kivymd"