Pandas plot doesn't show - python

When using this in a script (not IPython), nothing happens, i.e. the plot window doesn't appear :
import numpy as np
import pandas as pd
ts = pd.Series(np.random.randn(1000), index=pd.date_range('1/1/2000', periods=1000))
ts.plot()
Even when adding time.sleep(5), there is still nothing. Why?
Is there a way to do it, without having to manually call matplotlib ?

Once you have made your plot, you need to tell matplotlib to show it. The usual way to do things is to import matplotlib.pyplot and call show from there:
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
ts = pd.Series(np.random.randn(1000), index=pd.date_range('1/1/2000', periods=1000))
ts.plot()
plt.show()
In older versions of pandas, you were able to find a backdoor to matplotlib, as in the example below. NOTE: This no longer works in modern versions of pandas, and I still recommend importing matplotlib separately, as in the example above.
import numpy as np
import pandas as pd
ts = pd.Series(np.random.randn(1000), index=pd.date_range('1/1/2000', periods=1000))
ts.plot()
pd.tseries.plotting.pylab.show()
But all you are doing there is finding somewhere that matplotlib has been imported in pandas, and calling the same show function from there.
Are you trying to avoid calling matplotlib in an effort to speed things up? If so then you are really not speeding anything up, since pandas already imports pyplot:
python -mtimeit -s 'import pandas as pd'
100000000 loops, best of 3: 0.0122 usec per loop
python -mtimeit -s 'import pandas as pd; import matplotlib.pyplot as plt'
100000000 loops, best of 3: 0.0125 usec per loop
Finally, the reason the example you linked in comments doesn't need the call to matplotlib is because it is being run interactively in an iPython notebook, not in a script.

In case you are using matplotlib, and still, things don't show up in iPython notebook (or Jupyter Lab as well) remember to set the inline option for matplotlib in the notebook.
import matplotlib.pyplot as plt
%matplotlib inline
Then the following code will work flawlessly:
fig, ax = plt.subplots(figsize=(16,9));
change_per_ins.plot(ax=ax, kind='hist')
If you don't set the inline option it won't show up and by adding a plt.show() in the end you will get duplicate outputs.

I did just
import matplotlib.pyplot as plt
%matplotlib inline
and add line
plt.show()
next to df.plot() and it worked well for

The other answers involve importing matplotlib.pyplot and/or calling some second function manually.
Instead, you can configure matplotlib to be in interactive mode with its configuration files.
Simply add the line
interactive: True
to a file called matplotlibrc in one of the following places:
In the current working directory
In the platform specific user directory specified by matplotlib.get_configdir()
On unix-like system, typically /home/username/.config/matplotlib/
On Windows C:\\Documents and Settings\\username\\.matplotlib\\

Related

Jupyter shows plot with and without plt.show() but with an addition of extra line [duplicate]

I have an array A of shape (1000, 2000). I use matplotlib.pyplot to plot the array, which means 1000 curves, using
import matplotlib.pyplot as plt
plt(A)
The figure is fine but there are a thousand lines of:
<matplotlib.lines.Line2D at 0xXXXXXXXX>
Can I disable this output?
This output is what the plt function is returning (I presume here you meant to write plt.plot(A)). To suppress this output assign the return object a name:
_ = plt.plot(A)
_ is often used to indicate a temporary object which is not going to be used later on. Note that this output you are seeing will only appear in the interpreter, and not when you run the script from outside the interpreter.
You can also suppress the output by use of ; at the end (assuming you are doing this in some sort of interactive environment)
plot(A);
plt.show()
This way there is no need to create unnecessary variables.
E.g.:
import matplotlib.pyplot as plt
plt.plot(A)
plt.show()
use a semi-colon after the plot command
eg:
plt.imshow(image,cmap);
will display the graph and stop the verbose
To ignore warnings
import warnings
warnings.filterwarnings("ignore")
This will resolve your issue.

Codes in Ipython vs Pycharm

I am a newbie and the following question may be dumb and not well written.
I tried the following block of codes in Ipython:
%pylab qt5
x = randn(100,100)
y = mean(x,0)
import seaborn
plot(y)
And it delivered a plot. Everything was fine.
However, when I copied and pasted those same lines of codes to Pycharm and tried running, syntax error messages appeared.
For instance,
%pylab was not recognized.
Then I tried to import numpy and matplotlib one by one. But then,
randn(.,.) was not recognized.
You can use IPython/Jupyter notebooks in PyCharm by following this guide:
https://www.jetbrains.com/help/pycharm/using-ipython-jupyter-notebook-with-pycharm.html
You may modify code like the snippet below in order to run in PyCharm:
from numpy.random import randn
from numpy import mean
import seaborn
x = randn(10, 10)
y = mean(x, 0)
seaborn.plt.plot(x)
seaborn.plt.show()

statsmodels package code works in spyder's ipython console but not in python script

This is a python script in the Spyder IDE of Anaconda. I have Python 3.6.2. The last two lines do nothing (apparently) when I run the script, but work if I type them in the IPython console of Spyder. How do I get them to work in the script please?
# import packages
import os # misc operating system functions
import sys # system parameters and functions
import pandas as pd # data frame handling
import statsmodels.formula.api as sm # stats module
import matplotlib.pyplot as plt # matlab-like plotting
import numpy as np # big, fast arrays for maths
# set working directory to here
os.chdir(os.path.dirname(sys.argv[0]))
# read data using pandas
datafile = '1314 Powerview Pasture Potential.csv'
data1 = pd.read_csv(datafile)
#list(data) # to show column names
# plot some data
# don't know how to pop out a separate window
plt.scatter(data1['long'],data1['lat'],s=40,facecolors='none',edgecolors='b')
# simple multiple regression
Y = data1[['Pasture and Crop eaten t DM/ha']]
X = data1[['Net imported Supplements per Ha',
'LWT/ha',
'lat']]
result = sm.OLS(Y,X).fit()
result.summary()

scipy equivalent for MATLAB spy

I have been porting code for an isomap algorithm from MATLAB to Python. I am trying to visualize the sparsity pattern using the spy function.
MATLAB command:
spy(sparse(A));
drawnow;
Python command:
matplotlib.pyplot.spy(scipy.sparse.csr_matrix(A))
plt.show()
I am not able to reproduce the MATLAB result in Python using the above command. Using the command with only A in non-sparse format gives quite similar result to MATLAB. But it's taking quite long (A being 2000-by-2000). What would be the MATLAB equivalent of a sparse function for scipy?
Maybe it's your version of matplotlib that makes trouble, as for me scipy.sparse and matplotlib.pylab work well together.
See sample code below that produces the 'spy' plot attached.
import matplotlib.pylab as plt
import scipy.sparse as sps
A = sps.rand(10000,10000, density=0.00001)
M = sps.csr_matrix(A)
plt.spy(M)
plt.show()
# Returns here '1.3.0'
matplotlib.__version__
This gives this plot:
I just released betterspy, which arguably does a better job here. Install with
pip install betterspy
and run with
import betterspy
from scipy import sparse
A = sparse.rand(20, 20, density=0.1)
betterspy.show(A)
betterspy.write_png("out.png", A)
With smaller markers:
import matplotlib.pylab as pl
import scipy.sparse as sps
import scipy.io
import sys
A=scipy.io.mmread(sys.argv[1])
pl.spy(A,precision=0.01, markersize=1)
pl.show()

Disable the output of matplotlib pyplot

I have an array A of shape (1000, 2000). I use matplotlib.pyplot to plot the array, which means 1000 curves, using
import matplotlib.pyplot as plt
plt(A)
The figure is fine but there are a thousand lines of:
<matplotlib.lines.Line2D at 0xXXXXXXXX>
Can I disable this output?
This output is what the plt function is returning (I presume here you meant to write plt.plot(A)). To suppress this output assign the return object a name:
_ = plt.plot(A)
_ is often used to indicate a temporary object which is not going to be used later on. Note that this output you are seeing will only appear in the interpreter, and not when you run the script from outside the interpreter.
You can also suppress the output by use of ; at the end (assuming you are doing this in some sort of interactive environment)
plot(A);
plt.show()
This way there is no need to create unnecessary variables.
E.g.:
import matplotlib.pyplot as plt
plt.plot(A)
plt.show()
use a semi-colon after the plot command
eg:
plt.imshow(image,cmap);
will display the graph and stop the verbose
To ignore warnings
import warnings
warnings.filterwarnings("ignore")
This will resolve your issue.

Categories

Resources