How to make plots customizable in python - python

I have two issues with my python plot that would be grateful if anyone could help me with:
1- I wonder if it is possible in python to have the option for the plots after display to add horizontal or vertical lines, so that these new lines could be added, moved or deleted without the need to run the code again.
to say it more clearly, I am looking for additional features that adding them does not need to change the code and they only enable me to manually draw on the already plotted image.
2- I want to plot a very large image in the real size, So that I need to add the horizontal and vertical slide bars to be able to scroll up/down or left/right in the plot?
I need to combine these two ability for my project, can someone help me with that?

1- You can't physically draw on it, but you can make a plot in matplotlib interactive as follows:
import matplotlib.pyplot as plt
plt.ion() # turns on interactive mode
fig = plt.figure()
ax = fig.add_subplot()
plt.ylim(-10, 10)
plt.xlim(0, 10)
while True:
plt.axhline(float(input("number")))
fig.canvas.draw()
fig.canvas.flush_events() # draws
This program allows you to create horizontal lines based on user input.
I think you can solve 2 with tkinter, but that would be pretty difficult. There might also an easier way. See this stack overflow question for an example of an interactive plot in tkinter. I believe this plot can be made bigger and scrollable, but I am not sure.

Related

Inscribing Plot window in the console and do not want the plot window popping up separately

I am facing couple of issues. First, I wanted all the plots in a separate window. For this, I successfully changed the settings and I got the separate window. The problem is, I got all the plots in same figures, which is bad. Second issue is, how do I inscribe window pan to the Ipconsole? I donot want a separate window. I want this window inside the console?
For the first issue, you can have your plots in different figures by using figure this way:
import matplotlib.pyplot as plt
plt.figure()
# Plot your first graph(s)
plt.figure()
# Plot your other graph(s)
plt.show()
Each time you call figure, a new window is created. For more information on figure, you can check the doc

how to determine the figure size of an open figure using the gui tool?

Lets say I am plotting a pandas.DataFrame
df.plot(figsize = (10,10))
I usually start with the default figure size and adjust the figure size using the gui tool to achieve the format I want (making sure all legends look ok etc). However for the next plot, I don't want to repeat the same process. I would like to get the proper size and next time just call the plot with the hard-coded figure size that I got from tinkering with gui tool. Is there a way to get the current figure size from the gui?
Keep a reference to the plot axes:
ax = df.plot(figsize = (10,10))
You can then get the figure size later on using:
ax.get_figure().get_size_inches()

Do I need a figure? What are they for?

I have begun using matplotlib and I am somewhat confused as to why figures exist. Sometimes I see code where a figure is declared and then a plot is made, and sometimes I see things like this:
import numpy as np
import matplotlib.pyplot as plt
data = np.loadtxt('initial.dat','float')
plt.plot(data[:,0], data[:,1])
plt.xlabel("x (Angstroms)")
plt.ylabel("V (eV)")
plt.savefig('v.png',bbox_inches='tight')
plt.clf()
I read the documentation on figure and plot, but I don't get it. Why do figures exist?
A figure will always exist once you create some plot with matplotlib.
The introductory matplotlib page may help here:
The whole figure. The figure keeps track of all the child Axes, a smattering of ‘special’ artists (titles, figure legends, etc), and the canvas. (Don’t worry too much about the canvas, it is crucial as it is the object that actually does the drawing to get you your plot, but as the user it is more-or-less invisible to you). A figure can have any number of Axes, but to be useful should have at least one.
You can imagine the figure to be the white sheet of paper you draw a plot on. A figure has some size, maybe a background and most importantly it is the container for everything you draw into it. In most cases this will be one or more axes. If there wasn't any figure, there wouldn't be any sheet of paper to draw your plot to (you cannot draw a line in the air).
Even if you haven't explicitely created the figure, it is automatically created in the background.
import matplotlib.pyplot as plt
plt.plot([1,2,3])
# at this point we already have a figure, because the plot needs to live somewhere
# we can get a handle to the figure via
figure = plt.gcf()
Examples of when you explicitely need a figure:
If you want to create a second figure.
plt.plot([1,2,3])
plt.figure(2)
plt.plot([2,4,6])
If you want to set the figure size or other figure parameters.
plt.figure(figsize=(5,4), dpi=72)
If you want to change the padding of the subplot(s).
fig, ax=plt.subplots()
fig.subplots_adjust(bottom=0.2)

Save images of a matplotlib figure at different coordinates?

I want to create a big figure using matplotlib, and then save a few parts of it at different specific coordinates (so manual zooming after plt.show() is not an option - there is no guarantee I can zoom to some precise coordinates - or is there?). The picture is fairly large, so I don't want to generate it all over again and again, specifying xlim and ylim every time before plotting. Is there any way to change axes limits after the figure is created? And I am not using an ipython console, but I need to use it in a script.
There is no problem with using xlim and ylim here. Take the following example:
import matplotlib.pyplot as plt
plt.plot(range(20))
plt.savefig("1.png")
plt.xlim(0,10)
plt.savefig("2.png")
plt.xlim(0,30)
plt.savefig("3.png")
Here a diagonal line is plotted, then we zoom into the first half of the line, then we zoom back out. At each stage a new png file is created. There is no need for redrawing here.

Change dynamically the contents of a matplotlib plot

I while ago, I was comparing the output of two functions using python and matplotlib. The result was as good as simple, since plotting with matplotlib is quite easy: I just plotted two arrays with different markers. Piece of cake.
Now I find myself with the same problem, but now I have a lot of pair of curves to compare. I initially tried plotting everything with different colors and markers. This did not satisfy me since the ranges of each curve are not quite the same. In addition to this, I quickly ran out of colors and markers that were sufficiently different to identify (RGBCMYK, after that, custom colors resemble any of the previous ones).
I also tried subplotting each pair of curves, obtaining a window with many plots. Too crowded.
I tried one window per plot, too many windows.
So I was just wondering if there is any existing widget or if you have any suggestion (or a different idea) to accomplish this:
I want to see a pair of curves and then select easily the next one, with a slidebar, button, mouse scroll, or any other widget or event. By changing curves, the previous one should disappear, the legend should change and its axis as well.
Well I managed to do it with an event handler for mouse clicks. I will change it for something more useful, but I post my solution anyway.
import matplotlib.pyplot as plt
figure = plt.figure()
# plotting
plt.plot([1,2,3],[10,20,30],'bo-')
plt.grid()
plt.legend()
def on_press(event):
print 'you pressed', event.button, event.xdata, event.ydata
event.canvas.figure.clear()
# select new curves to plot, in this example [1,2,3] [0,0,0]
event.canvas.figure.gca().plot([1,2,3],[0,0,0], 'ro-')
event.canvas.figure.gca().grid()
event.canvas.figure.gca().legend()
event.canvas.draw()
figure.canvas.mpl_connect('button_press_event', on_press)
Sounds like you want to embed matplotlib in an application. There are some resources available for that:
user interface examples
Embedding in WX
I really like using traits. If you follow the tutorial Writing a graphical application for scientific programming , you should be able to do what you want. The tutorial shows how to interact with a matplotlib graph using graphical user interface.

Categories