Is there any way to ask Basemap not show the plot? - python

I am trying to use mpl_toolkits.basemap on python and everytime I use a function for plotting like drawcoastlines() or any other, the program automatically shows the plot on the screen.
My problem is that I am trying to use those programs later on an external server and it returns 'SystemExit: Unable to access the X Display, is $DISPLAY set properly?'
Is there any way I can avoid the plot to be shown when I use a Basemap function on it?
I just want to save it to a file so later I can read it externally.
My code is:
from mpl_toolkits.basemap import Basemap
import numpy as np
m = Basemap(projection='robin',lon_0=0)
m.drawcoastlines()
#m.fillcontinents(color='coral',lake_color='aqua')
# draw parallels and meridians.
m.drawparallels(np.arange(-90.,120.,10.))
m.drawmeridians(np.arange(0.,360.,60.))

Use the Agg backend, it doesn't require a graphical environment:
Do this at the very beginning of your script:
import matplotlib as mpl
mpl.use('Agg')
See also the FAQ on Generate images without having a window appear.

The easiest way is to put off the interactive mode of matplotlib.
from mpl_toolkits.basemap import Basemap
import matplotlib.pyplot as plt
import numpy as np
#NOT SHOW
plt.ioff()
m = Basemap(projection='robin',lon_0=0)
m.drawcoastlines()
#m.fillcontinents(color='coral',lake_color='aqua')
# draw parallels and meridians.
m.drawparallels(np.arange(-90.,120.,10.))
m.drawmeridians(np.arange(0.,360.,60.))

Related

Figure not displayed with matplotlib.use('Agg')

I work with matplotlib. When I add the following lines, the figure is not displayed.
import matplotlib
matplotlib.use('Agg')
here is my code :
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plot
import numpy as np
from mpl_toolkits.mplot3d import Axes3D
fig = plot.figure(figsize=(12,9))
def convert_sin_cos(x):
fft_axes = fig.add_subplot(331)
y = np.cos(x)
fft_axes.plot(x,y,'g*')
for i in range(3):
fft_axes = fig.add_subplot(332)
x=np.linspace(0,10,100)
fft_axes.plot(x,i*np.sin(x),'r+')
plot.pause(0.1)
convert_sin_cos(x)
Thanks
That's the idea!
When I run your code, the console says:
matplotlibAgg.py:15: UserWarning: Matplotlib is currently using agg, which is a non-GUI backend, so cannot show the figure.
How can it be useful? When you're running matplotlib code in a terminal with no windowing system, for example: a cluster (running the same code with different inputs, getting lot of results and without the need to move the data I can plot whatever I need).

Why can't I create a 3d scatter plot in Python on my desktop?

I am trying to use the 3D scatter plot object in python. And I have successfully done this on my laptop. However, I can not copy and paste code onto my desktop. When I do this I get an error. I will attach my the section of my code below that is giving me trouble. I am using Anaconda to run my code. I will note that my laptop uses python 3.6 and my desktop uses 3.7, but I do not think that is causing it. The error I is get is as follows. "ValueError: Unknown projection '3d'"
import numpy as np
from scipy import optimize
import time
from sklearn.metrics import mean_squared_error
import matplotlib.pyplot as plt
import pandas as pd
from sklearn import preprocessing
from sklearn.svm import SVR
import multiprocessing as mp
from obj_class import objective_class
import pdb
import scipy.integrate as integrate
def create3d():
grid_matrix = np.array([[1,1,1,1],[2,2,2,2],[3,3,3,3]])
fig = plt.figure()
ax = plt.axes(projection='3d')
p = ax.scatter3D(grid_matrix[:,0],grid_matrix[:,1] ,grid_matrix[:,2] , c=grid_matrix[:,3], cmap='viridis')
cb = fig.colorbar(p)
ax.set_xlabel('X')
ax.set_ylabel('Y')
ax.set_zlabel('Z')
ax.set_title(' Scatter Plot')
In order to use a 3d projection in matplotlib <= 3.1 you need to import axes3d, i.e.
from mpl_toolkits.mplot3d import Axes3D
From matplotlib >= 3.2, no extra import is necessary. So possibly you are running different matplotlib versions on both computers.
If you are running your code within an iPython kernel, Jupyter notebook for example,
then you only need to perform each import once and you will be able to run any code which relies on said import until the kernel is shutdown. However, in order to run the script in a self contained fashion you will need that import included in your script.

Seaborn displays different color for different run

I followed the setting from here to make matplotlib/seaborn available to display in Zeppelin. However, with the following code:
%python
import seaborn as sns
import matplotlib
import numpy as np
matplotlib.use('Agg')
import matplotlib.pyplot as plt
plt.rcdefaults()
import StringIO
def show(p):
img = StringIO.StringIO()
p.savefig(img, format='svg')
img.seek(0)
print "%html <div style='width:600px'>" + img.buf + "</div>"
""" Prepare your plot here ... """
# Use the custom show function instead of plt.show()
x = np.random.randn(100)
ax = sns.distplot(x)
show(sns.plt)
It is strange that the displayed figure show the desired lightblue color the first time I run the code but will display different colors if I execute the same piece of code. Is there a way to force seaborn to keep constant color being displayed? Thanks.
It's not entirely clear what is meant by "running a second time".
However you may try to actually close the figure before running it again. E.g.
plt.close("all")
in order to make sure, a new figure is created which should have the same default color every time.

Jupyter NoteBook: draw a graph on the Notebook instead of save the file to the disk

I have the following code:
Is it possible to print the graph just inside the Notebook instead of saving as a file? Thanks!
If you are looking to plot the plots inline inside your jupiter-notebook:
import matplotlib.pyplot as plt
%matplotlib inline
Yes, use matplotlib:
import matplotlib.pyplot as plt
nx.draw(G)
plt.show()
source
Use draw in the following manner :
draw(G, show='ipynb')
If you want all graphs to be drawn inline, then you can set a global parameter.
from nxpd import nxpdParams
nxpdParams['show'] = 'ipynb'
draw(G)
But im not sure this will work with Jupyter, this will work for ipython though.

module getting stuck on show() in ipython

Hello I created a module in the ipython text editor and then called it in the ipython notebook and it freezes when I call show() from matplotlib. I am running on a surface pro windows 10. I have checked for answers and I found that using import matplotlib as mpl
mpl.use('TkAgg')
in the beginning of my module worked the first time and then every time I tried to run after it has killed my kernel. Here is my module which is called Take_Home.py:
import numpy as np
import matplotlib as mpl
import pdb
#mpl.use('TkAgg')
import matplotlib.pyplot as plt
import matplotlib.mlab as ml
def statistics(array,bin_size):
#calculate mean and standard deviation of array
mean=np.mean(array)
std=np.std(array)
#get the gaussian fit of the data
gaussian=ml.normpdf(array,mean,std)
#plot the normalized histogram
plt.hist(array,bins=np.arange(np.min(array), np.max(array) + bin_size, bin_size),normed=True)
#plot the gaussian function over the histogram
plt.plot(array,gaussian,'.k')
#this attempts to show the plot but doesn't work
plt.show()
#saves the plot to a PDF
plt.savefig('Statistics.pdf')
and here is the ipython notebook that calls the module:
import Take_Home as th
import numpy as np
import matplotlib.pyplot as plt
#initialize an array of 1000 elements and set them all to 1
rd=np.arange(0,1000)
rd[:]=1
#change the array to have all random numbers with a std of 2 and a mean of 1
rd=rd*(2*np.random.randn(1,1000)+1)
#transpose it because the error message said so
rd=np.transpose(rd)
#declare bin size
binsize=0.2
#use method inside module
th.statistics(rd,binsize)
I just need to show the plot and I don't know why it's working any help would be much appreciated thank you!

Categories

Resources