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

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).

Related

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.

Pycharm: show x/y coordinates with matplotlib automatically

If I plot with ipython, I automatically see the x/y coordinates when I move with the mouse over the canvas (see bottom right in screenshot):
import matplotlib.pyplot as plt
import numpy as np
my_random = np.random.random(5)
plt.plot(my_random)
plt.show()
How can the same achieved with Pycharm (my plots appear in the SciView toolwindow)?
If not: is there perhaps an easy workaround for it? (and do I have more possibilities if the plot does not appear in the SciView toolwindow?)
using TkAgg it works:
import matplotlib
matplotlib.use('TkAgg')
import numpy as np
import matplotlib.pyplot as plt
my_random = np.random.random(5)
plt.plot(my_random)
plt.show()

plt.show() not executing properly

Currently, I am attempting to follow along with a Sentdex YouTube tutorial video (https://www.youtube.com/watchv=cExOVprMlQg&list=PLQVvvaa0QuDe6ZBtkCNWNUbdaBo2vA4RO), however I am running into some difficulties with plt.show(). I have written this script nearly verbatim as detailed in this video and I have turned to StackOverflow to update any syntax, yet I have not been able to actually view this graph. Nothing comes up when I run the script, the shell just spits out '>>'. I have changed backends, unistalled, upgraded and reinstalled matplotlib. I've also tried this script on the exact version of Python seen in this video as well as 3.6.1 and a few others on OS X and Windows 10 via Parallels - still running into the same issue.
Here is my code thus far:
import matplotlib
import matplotlib.pyplot as plt
import matplotlib.ticker as mticker
import matplotlib.dates as mdates
import numpy as np
import pylab
def graphRawFX():
date, bid, ask = np.loadtext('GBPUSD1d.txt', unpack=True,
delimiter='-',
converters={0: mdates.strpdate2numb('%Y%m%d%H%M%S')})
fig = plt.figure(figsize=(10,7))
ax1 = plt.subplot2grid((40,40), (0), rowspan=40, colspan=40)
ax1.plot(date, bid)
ax1.plot(date, ask)
ax1.xaxis.set_major_formatter(mdate.DateFormatter('%Y-%m-%d %H:#M:#S'))
for label in ax1.axis,get_xticklabels():
label.set_rotation(45)
ply.gca().get_yaxis().get_major_formatter().set_useOffset(False)
plt.grid(True)
plt.show()
pylab.show()
Any thoughts on a solution?
You defined a function, which plots. But you never call the function! Your script is empty from python's perspective.
Add graphRawFX() at the end, without any indentation to actually call the function.
If this code is by any means incomplete and not your issue, check your install and clean up the code. The whole import pylab thing looks unwanted. Also ply does not exist and so on. Start with the basics, the official examples and the docs, not with some yt-video which uses tons of (advanced) stuff.
I have it working (mac OS). Just try to copy paste to see if there's some typing problem. (it was working without "import pylab" and the "pylab.show()" I have just put it to have the same code you have.
import matplotlib
import matplotlib.pyplot as plt
import matplotlib.ticker as mticher
import matplotlib.dates as mdates
import numpy as np
import pylab
def graphRawFX():
date,bid,ask = np.loadtxt('GBPUSD1d.txt', unpack=True, delimiter=',',converters={0:mdates.strpdate2num('%Y%m%d%H%M%S')})
fig = plt.figure(figsize=(10,7))
ax1 = plt.subplot2grid((40,40), (0,0), rowspan=40, colspan=40)
ax1.plot(date,bid)
ax1.plot(date,ask)
plt.gca().get_yaxis().get_major_formatter().set_useOffset(False)
ax1.xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m-%d %H:%M:%S'))
for label in ax1.xaxis.get_ticklabels() :
label.set_rotation(45)
ax1_2=ax1.twinx()
ax1_2.fill_between(date,0, (ask-bid),facecolor='g',alpha=.3)
plt.subplots_adjust(bottom=.23)
plt.grid(True)
plt.show()
pylab.show()
graphRawFX()

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.

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

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.))

Categories

Resources