I have this simple python 3 example:
import librosa
import numpy as np
import matplotlib.pyplot as plt
# template, Fs = librosa.load('example.wav')
t = np.arange(0, 10)
plt.plot(t)
plt.show()
But as soon as I outcomment librosa.load(...) the program crashes with this error message:
/usr/lib/python3.6/site-packages/matplotlib/backends/backend_qt5.py:124: Warning: g_main_context_push_thread_default: assertion 'acquired_context' failed
qApp = QtWidgets.QApplication([b"matplotlib"])
There is still a new window opened for the plot, but it's completely empty.
Have the exact same problem. Use scipy.io.wavfile.read(path) instead.
Related
I am using Jupyter Notebook while running the below code,
import matplotlib.pyplot as plt
import numpy as np
a = np.arange(10)
b = np.sin(a)
plt.plot(a,b)
print("After 3 clicks:")
x = plt.ginput(3)
print(x)
plt.show()
While running this code I get the below warning
UserWarning: Matplotlib is currently using module://matplotlib_inline.backend_inline, which is a non-GUI backend, so cannot show the figure.
x = plt.ginput(3)
Due to this issue, I am not able to click the points on graph nor I am getting the clicked points in output.
The python in my system is of version is 3.9.7 and matplotlib is of version 3.4.3.
The issue is resolved. I used matplotlib.use() before importing pyplot.
import matplotlib
matplotlib.use('Qt5Agg')
import matplotlib.pyplot as plt
import numpy as np
a = np.arange(10)
b = np.sin(a)
plt.plot(a,b)
print("After 3 clicks:")
x = plt.ginput(3)
print(x)
plt.show()
matplotlib.use('Qt5Agg') this changed the non -gui backend to GUI backend of Qt5Agg.
For the life of me, I can't get to render plots in RMarkdown using Python. The plots display in my Python Editor, but not when I switch to RStudio trying to build a PDF/HTML report. I've been all over the internet, everyone has an answer, but none has the solution to my issue. Here's the error message I get the attached error below:
Below I made up some data to show what I'm trying to achieve. Once the application hits the seaborn line it produces the attached error message in RStudio
knitr::opts_chunk$set(echo = TRUE)
library(reticulate)
Importing Required Packages
import pandas as pd
import numpy as np
from scipy.stats import uniform # for training-and-test split
import statsmodels.api as sm # statistical models (including regression)
import statsmodels.formula.api as smf # R-like model specification
import matplotlib.pyplot as plt # 2D plotting
import seaborn as sns
x = np.random.normal(0, 1, 20)
y = np.random.normal(0, 2, 20)
sns.scatterplot(x, y)
I found the answer here
All I needed was to add these two lines in the R setup chunk below the library(reticulate) call
matplotlib <- import("matplotlib")
matplotlib$use("Agg", force = TRUE)
#%%
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 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.
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!