Reputation: 387
I wonder if it is possible to update a parameter such as the line color of an already plotted graph that doesn't wrap on destroying the graph and creating another one.
Example: I plot a graph then I create a few horizontal green lines on it by clicking. Now I want to change the blue main line of the graph to the color red without losing the horizontal green lines that were created.
Something like:
import matplotlib.pyplot as plt
c = None
fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot([1,2,3],[1,2,3], color = c)
def onclick(event):
plt.ion()
plt.hlines(event.ydata,event.xdata-0.1,event.xdata+0.1,
colors='green',linestyle='solid')
cid = fig.canvas.mpl_connect('button_press_event', onclick)
def change_color():
c = 'r'
# ???
plt.show()
change_color() # running this function will update the plot line color to red
Upvotes: 0
Views: 2254
Reputation: 87556
You need to capture the artist created by the hlines
call:
fig, ax = plt.subplots()
arts = ax.hlines([.5, .75], 0, 1, lw=5)
Which returns a LineCollection
object. You can programtically modify it
arts.set_color(['sage', 'purple'])
and to get the window to update you will need to call
fig.canvas.draw()
(this last bit is no longer true on master when at the repl with pyplot imported)
I did something a bit fancier here and used hlines
to draw more than one line and set more than one color, but it works the same with only one line as well.
Upvotes: 3