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!
Related
#%%
from Utils.ConfigProvider import ConfigProvider
import os
import cv2
import numpy as np
from matplotlib import pyplot as plt
config = ConfigProvider.config()
and
#%%
inspected = cv2.imread(config.data.inspected_image_path, 0)
reference = cv2.imread(config.data.reference_image_path, 0)
diff = np.abs(inspected - reference)
plt.figure()
plt.title('inspected')
plt.imshow(inspected)
plt.show()
note config.data.inspected_image_path and config.data.reference_image_path are valid paths.
No errors appear, but no images are shown as well.
Running the same code from a python file does show the image.
I have something missing from the notebook.
This happens both when running using jupyter notebook and directly from PyCharm (pro)
How do I get to see images? all other answers I found just tell me to plt.show() but this obviously does not work.
I don't mind a cv2 solution as well.
You need to set a matplotlib backend.
You can do this with
%matplotlib inline
If you want to be able to interact with the plot, use
%matplotlib notebook
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).
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.
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.))
I'm using python3 with matplotlib. I've encountered some issues with the pyplot.draw() function : no graphic window appears on my screen when I run my script.
The pyplot.plot() function works just fine :
#!/usr/bin/python3.2
#-*-coding:utf-8-*
from matplotlib import pyplot as plt
import numpy as np
plt.figure(1)
plt.plot(np.arange(35), np.arange(25),'r')
plt.show()
In this situation ./myscript.py displays the graphic window.
But when I try to make an simple animation :
import numpy as np
from matplotlib import pyplot as plt
from time import sleep
plt.ion()
nb_images = 1000
tableau = np.random.normal(10,10,(nb_images, 100, 100))
image = plt.imshow(tableau[0,:,:])
for k in np.arange(nb_images)
image.set_data(tableau[k,:,:])
print(k)
plt.draw()
sleep(0.1)
./myscript.py does the calculation (my terminal displays the "k" value) but the graphic window doesn't appear on my screen...
The problem is the same when I'm using python2.x
The backend in the configuration file "matplotlibrc" (python3.2) is "tkagg". I've already tried to change it but still no graphic window to admire my animation....
Thanks for you help.