add line to graph after pushing button in python

You can create a line graph and add a line to it after pushing a button in Python using the matplotlib library. Here is an example of how you can achieve this:

main.py
import matplotlib.pyplot as plt

def add_line(event):
    x_values = [1, 2, 3, 4, 5]
    y_values = [1, 4, 9, 16, 25]
    plt.plot(x_values, y_values, 'r--')

fig, ax = plt.subplots()
plt.subplots_adjust(bottom=0.2)

# Create a button and specify its position
button_ax = plt.axes([0.7, 0.05, 0.2, 0.075])
button = plt.Button(button_ax, 'Add Line')
button.on_clicked(add_line)

plt.show()
389 chars
17 lines

In this example, we first define a function add_line that will be called when the button is clicked. Inside this function, we define the x and y values for the new line to be added and use the plt.plot() function to add the line to the graph.

We then create the figure and axes using plt.subplots(), adjust the position of the axes so that the button does not overlap with the graph using plt.subplots_adjust(), and create the button using plt.Button(). We specify the position of the button using the plt.axes() function.

Finally, we call button.on_clicked() to connect the button to the add_line function and display the graph using plt.show().

When you run this code, a graph will be displayed with a button labeled "Add Line". When you click the button, it will add a red dashed line to the graph.

Note: This code assumes that you have matplotlib installed. You can install it using pip install matplotlib.

related categories

gistlibby LogSnag