Getdist plot not showing up in console - python

I'm using getdist to plot some simulation results.
In jupyter writing just this line
g = plots.getSubplotPlotter()
g.triangle_plot([samples, samples2], filled=True)
Python will show plots as we can see here.
Now if we want to write it in Python shell and run it with IDLE, this does not produce any plot. plt.show() does not work here.
How to instruct python or matplotlib to show the plots and save them?

The problem is that getdist sets the backend to Agg (in this line), which is a non-interactive backend and hence cannot produce an interactive figure via plt.show().
This is pretty bad style, because the user should select the backend, not the package. You might want to inform the developpers about this design flaw.
Anyways it would be possible to switch the backend after importing getdist, via plt.switch_backend(..). As backend you would need to use any interactive backend you have available, e.g. "Qt5Agg" or "TkAgg".
import numpy as np
from getdist import plots, MCSamples
import matplotlib.pyplot as plt
plt.switch_backend("Qt5Agg")
# .. some code ..
g = plots.getSubplotPlotter()
g.triangle_plot([samples, samples2], filled=True)
plt.show()

Related

How to get good plots in Spyder python ? (Inline and Qt5)

When i plot in Spyder with the Backend Qt5 in graphics ( the window that pops with the plot) i don't get things aesthetically beautiful. The title sometimes is not showing, the labels, ... All in all it is just not good looking. But when it is plotted "inline" it is very well presented.
What I want is :
I want the plot with the Backend Qt5 option very well presented like the Backend Inline option.
The code is this :
import numpy as np
from matplotlib import pyplot as plt
plt.plot(np.linspace(0,2, num = 5))
plt.title('Blabla')
plt.xlabel('Anything')
plt.ylabel('Everything')
What I get with the Backend Qt5 option
What I get with the Backend Inline option
I think the command %matplotlib qt might be the solution to this problem. You should write the line in the IPython Console.
The problem was the use of this line in order to increase the quality of the plots:
plt.rcParams['figure.dpi'] = 300
In Qt5 it's not required.

Jupyter and %matplotlib inline lost axis

I am having a really weird issue with using the %matplotlib inline code in my jupyter notebook for plotting graphs using both pyplot and the pandas plotting function.
The problem is they show up without any axes, and basically just show the graph area without anything aside from data points.
I found adding:
import matplotlib as mpl
mpl.rcParams.update(mpl.rcParamsDefault)
reverse it, but I find it odd that should do that every time as the effect disappears as soon as I run %matplotlib inlinecommand.
an example could be
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
%matplotlib inline
plt.scatter(A,A)
plt.tight_layout()
plt.xlabel('here')
plt.show()
This would generate the graph below:
Weird enough if I uses the savefig it get plotted with the axis, if I uses the right-click -> new output -> save as figure, I also get the graph with the figures !!
like this:
Can anyone help me understand what is wrong, which global setting did I mess up, and how do I revert it?
(I don't remember messing around with any settings aside from some settings for pandas, but don't think they should have had an impact)
as mentioned running mpl.rcParams.update(mpl.rcParamsDefault) command does bring it back to normal until I run %matplotlib inline` again !!
Any help would be much appreciated.
Okay I am sorry I think I can answer the question myself now.
With the helpfull #Mr. T asking for the imgur link made me realize what was going on. I had starting using the dark jupyter lab theme, and the graph would generate plots with transparent background, ie. the text and lines where there, but I just couldn't see them.
The trick is to change the background color preferably globally, but that will be a task for tomorrow.

Why am I getting UserWarning: Matplotlib is currently using ps, which is a non-GUI backend, so cannot show the figure

This is not in a jupyter notebook so this is not a duplicate of this question, but my code is:
from gluoncv import model_zoo, data, utils
from matplotlib import pyplot as plt
...
plt.show()
The error I'm getting is:
/figure.py:445: UserWarning: Matplotlib is currently using ps, which is a non-GUI backend, so cannot show the figure.
% get_backend())
I created a repl at https://repl.it/#shamoons/WelloffHarmfulMineral
If it matters, I'm using OS X. What do I need to do to get the image to show?
You can use
matplotlib.use("TkAgg")
instead of
matplotlib.use("PS")
when developing on MacOS.
Please note that the import should be before importing plt, like this:
import matplotlib
matplotlib.use('TkAgg')
from matplotlib import pyplot as plt
matplotlib.use('PS') and plt.show() are mutually exclusive. You need to decide:
Do you want to show the figure on screen? Solution: Remove the line matplotlib.use('PS').
Do you want to use the PS backend? This seems unlikely, because there is rarely a reason to set the backend to something non-interactive unless working on a server. Anyways, solution: Replace plt.show() by plt.savefig("filname.ps").

Use both matplotlib inline and qt in jupyter notebook

I am using Jupyter (with IPython) to analyze research data, as well as export figures. I really like the notebook approach offered by Jupyter: when I revisit an experiment after a long time, I can easily see how the figures correspond to the data. This is of course using the inline backend.
However, when I want to explore new data, I prefer to use the QT backend. It is faster than the inline one, and allows to easily scale, zoom in and out, and nicely displays the X and Y coordinates in the bottom left corner. Moreover, I can use the QT backend to determine good x and y limits to use in the inline backend.
I have tried using the %matplotlib notebook magic, but it is simply too slow. For some experiments I am plotting ~500 spectra (each consists of ~1000 data points), which is already slow in the inline backend. Even with less data points, the notebook backend is just too slow to use.
Therefore, I would like to use both the QT backend, and the inline backend whenever I plot something. (So, whenever I execute a cell which plots data, it should both display the inline image, and pop up a QT backend window). This way, I still have a nice overview of plots in my notebook, while also allowing me to easily explore my data. Is there a way to achieve this?
As far as I know it is not possible to use more than one backend at once.
What I do is to switch backend and replot. I have done it with matplotlib.use() or %matplotlib <backend>, according to which version or environment I was working in.
I had the impression that this sometimes doesn't work or maybe it is not responsive, so I need to restart the environment. I imagine it is not easy to maintain it, so I am even surprised it works so smoothly almost always.
Available backends can be listed with:
matplotlib.rcsetup.interactive_bk
matplotlib.rcsetup.non_interactive_bk
matplotlib.rcsetup.all_backends
Hopefully here there are other useful info:
https://matplotlib.org/stable/tutorials/introductory/usage.html
This allows you to run QtConsole, plotting with the plotSin function, both inline and through the QtConsole.
import matplotlib
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
..
def plotChirp(Type, Exp, Rand):
# Orignal Chirp Funciton From:
# http://stackoverflow.com/questions/19410042/how-to-make-ipython-notebook-matplotlib-plot-inline
x = np.linspace(0, 3*np.pi, Rand)
plt.plot(x, np.sin(x**int(Exp)))
plt.title('A simple chirp ' + Type)
plt.show()
..
plotChirp("A", 5, 200) # Plots inline if you choose
%connect_info # For your own connection
%qtconsole
QtConsole opens and now you can call your function to plot externally..
Using %matplotlib qt allows for printing in a loop, but unfortunately it seems to overlap the plots. Looking into subplots as a possible solution.
%matplotlib qt
for i in range(0,2):
if i == 0:
plotChirp("B",1, 400)
else:
plotChirp("c",6, 1000)

Matplotlib - Tcl_AsyncDelete: async handler deleted by the wrong thread?

I'm asking this question because I can't solve one problem in Python/Django (actually in pure Python it's ok) which leads to RuntimeError: tcl_asyncdelete async handler deleted by the wrong thread. This is somehow related to the way how I render matplotlib plots in Django. The way I do it is:
...
import matplotlib.pyplot as plt
...
fig = plt.figure()
...
plt.close()
I extremely minimized my code. But the catch is - even if I have just one line of code:
fig = plt.figure()
I see this RuntimeError happening. I hope I could solve the problem, If I knew the correct way of closing/cleaning/destroying plots in Python/Django.
By default matplotlib uses TK gui toolkit, when you're rendering an image without using the toolkit (i.e. into a file or a string), matplotlib still instantiates a window that doesn't get displayed, causing all kinds of problems. In order to avoid that, you should use an Agg backend. It can be activated like so --
import matplotlib
matplotlib.use('Agg')
from matplotlib import pyplot
For more information please refer to matplotlib documentation -- http://matplotlib.org/faq/howto_faq.html#matplotlib-in-a-web-application-server
The above (accepted) answer is a solution in a terminal environment. If you debug in an IDE, you still might wanna use 'TkAgg' for displaying data. In order to prevent this issue, apply these two simple rules:
everytime you display your data, initiate a new fig = plt.figure()
don't close old figures manually (e.g. when using a debug mode)
Example code:
import matplotlib
matplotlib.use('TkAgg')
from matplotlib import pyplot as plt
fig = plt.figure()
plt.plot(data[:,:,:3])
plt.show()
This proves to be the a good intermediate solution under MacOS and PyCharm IDE.
If you don't need to show plots while debugging, the following works:
import matplotlib
matplotlib.use('Agg')
from matplotlib import pyplot as plt
However, if you would like to plot while debugging, you need to do 3 steps:
1.Keep backend to 'TKAgg' as follows:
import matplotlib
matplotlib.use('TKAgg')
from matplot.lib import pyplot as plt
or simply
import matplotlib.pyplot as plt
2.As Fábio also mentioned, you need to add fig(no. #i)=plt.figure(no.#i) for each figure #i. As the following example for plot no.#1, add:
fig1 = plt.figure(1)
plt.plot(yourX,yourY)
plt.show()
3.Add breakpoints. You need to add two breakpoints at least, one somewhere at the beginning of your codes (before the first plot), and the other breakpoint at a point where you would like all plots (before to the second breakpoint) are plotted. All figures are plotted and you even don't need to close any figure manually.
For me, this happened due to parallel access to data by both Matplotlib and by Tensorboard, after Tensorboard's server was running for a week straight.
Rebotting tensorboard tensorboard --logdir . --samples_per_plugin images=100 solved this for me.
I encountered this problem when plotting graphs live with matplotlib in my tkinter application.
The easiest solution I found, was to always delete subplots. I found you didn't need to instantiate a new figure, you only needed to delete the old subplot (using del subplot), then remake it.
Before plotting a new graph, make sure to delete the old subplot.
Example:
f = Figure(figsize=(5,5), dpi=100)
a = f.add_subplot(111)
(For Loop code that updates graph every 5 seconds):
del a #delete subplot
a = f.add_subplot(111) #redefine subplot
Finding this simple solution to fix this "async handler bug" was excruciatingly painful, I hope this helps someone else :)

Categories

Resources