[Python] Matplotlib button "Save data as CSV" in the toolbar next to the "Save the figure as...

Discussão em 'Python' iniciado por Stack, Junho 19, 2025.

  1. Stack

    Stack Membro Participativo

    This works to add a "Save as CSV" button in a Matplotlib plot:

    import matplotlib.pyplot as plt
    from matplotlib.widgets import Button
    import csv
    X = [1, 2, 3, 4, 5]
    Y = [2, 3, 5, 7, 11]
    def save_as_csv(event):
    file_path = 'data.csv'
    with open(file_path, 'w', newline='') as file:
    writer = csv.writer(file)
    writer.writerow(['X', 'Y'])
    writer.writerows(zip(X, Y))
    print(f'Data saved to {file_path}')
    fig, ax = plt.subplots()
    plt.plot(X, Y, linestyle='None', marker='.', markersize=5)
    plt.subplots_adjust(bottom=0.2)
    ax_button = plt.axes([0.81, 0.05, 0.1, 0.075])
    button = Button(ax_button, 'Save CSV')
    button.on_clicked(save_as_csv)
    plt.show()


    How to have the button in the toolbar, next to the "Save the figure" (diskette icon), with TkAgg backend?

    Continue reading...

Compartilhe esta Página