0

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
Victor José
  • 367
  • 1
  • 4
  • 12

1 Answers1

3

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.

tacaswell
  • 84,579
  • 22
  • 210
  • 199
  • Sorry, but maybe I didn't understand it right. What it does is to get the ID of the created hlines and change their colors? What about changing the main plot color ( ax.plot([1,2,3],[1,2,3], color = c ) ? – Victor José Jun 06 '15 at 18:11
  • Ops, nevermind. I got the hang of it. Thank you for your tips (especially the fig.canvas.draw() ) :) – Victor José Jun 07 '15 at 03:18
  • @VictorJosé Sorry, I was confused by what you were trying to do, I thought you wanted to change the colors of the hlines. – tacaswell Jun 07 '15 at 18:48
  • You should also read http://stackoverflow.com/questions/15858192/how-to-set-xlim-and-ylim-for-a-subplot-in-matplotlib/15858264#15858264 which is a longer write up of how to use the OO interface. – tacaswell Jun 07 '15 at 18:49