0

I am interested in using the interact function to use a slider to adjust the position of text in a matplotlib plot (you know, instead of adjusting the position, running the code, and repeating 1000 times).

Here's a simple example of a plot

import matplotlib.pyplot as plt
x=0.2
y=0.9
plt.text(x, y,'To move',size=19)
plt.show()

and some interact code

from __future__ import print_function
from ipywidgets import interact, interactive, fixed
import ipywidgets as widgets
def f(x):
    return x
interact(f, cx=0.2)

I'm wondering how I can combine these to generate a plot with the text along with a slider that will interactively move the text based on the specified value for x. Is this possible? What if I want to do the same for y?

Thanks in advance!

Dance Party
  • 3,459
  • 10
  • 42
  • 67

1 Answers1

2

Here you go:

%matplotlib inline
import matplotlib.pyplot as plt
from ipywidgets import interact

def do_plot(x=0.2, y=0.9):
    plt.text(x, y,'To move',size=19)
    plt.show()

interact(do_plot)
nicolaskruchten
  • 26,384
  • 8
  • 83
  • 101
  • Thank so much! So it looks like all I have to do is put any MPL chart within the do_plot function to interact with text placement. This will save me many hours of frustration. A follow-up question: I see from the GitHub documentation that I can replace line 4 with def do_plot(y=1,x=widgets.IntSlider(min=-1,max=1,step=0.01,value=0.05)): to define the steps and range, but I'm having a hard time getting fine-grained control (it doesn't behave as I expected in that it jumps from 0 to 1). Or can I replace the slider with a box in which I can enter a float? – Dance Party Mar 05 '16 at 03:22
  • I just played around with it some more and I see now that I can manually adjust the number next to the slider, so I think I'm all set for now. Thanks again! – Dance Party Mar 05 '16 at 03:32