backend_qt5.py "'figure' is an unknown keyword argument, In matplotlib - python

I am trying to run a simple code to plot my data using matplotlib in python2.7.10 :
import matplotlib.pyplot as plt
y=[23,35,43,54,76]
x=[2,4,5,6,7]
plt.plot(y,x)
I am getting the error:
super(FigureCanvasQTAggBase, self).__init__(figure=figure)
File "/usr/local/lib/python2.7/dist-packages/matplotlib/backends/backend_qt5.py", line 239, in __init__
super(FigureCanvasQT, self).__init__(figure=figure)
TypeError: 'figure' is an unknown keyword argument
How can I fix it?

This seems to be a duplicate of: matplotlib Qt5Agg backend error: 'figure' is an unknown keyword argument, which I just posted an answer for, and duplicated below:
I had the same issue. I found the solution here
Specifically, the following now works:
import matplotlib
matplotlib.use('Qt4Agg')
from matplotlib import pyplot as plt
plt.figure(figsize=(12,8))
plt.title("Score")
plt.show()

Just adding to Marc's answer. If you are using Spyder,
matplotlib.use('Qt4Agg')
may not work well because matplotlib has been imported when you open Spyder.
Instead you can go to (in Spyder) Tools - Preferences -IPython console - Graphics to change the backend and restart Spyder.

adding to this, i ran into this problem when i wanted to plot my values for my KNN training sets and test set results.
using TkAgg also fixes the problem
"matplotlib.use('TkAgg')"
import matplotlib
matplotlib.use('TkAgg')
#matplotlib.use('Qt4Agg')
import matplotlib.pyplot as plt
plt.figure(figsize=(12,8))
plt.title("Score")
plt.show()

Related

When I run '''sns.histplot(df['price'])''' in pycharm I get the code output but no graph, why is this?

I'm using pycharm to run some code using Seaborn. I'm very new to python and am just trying to learn the ropes so I'm following a tutorial online. I've imported the necessary libraries and have run the below code
import pandas as pd
import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt
# import the data saved as a csv
df = pd.read_csv('summer-products-with-rating-and-performance_2020-08.csv')
df["has_urgency_banner"] = df["has_urgency_banner"].fillna(0)
df["discount"] = (df["retail_price"] -
df["price"])/df["retail_price"]
df["rating_five_percent"] = df["rating_five_count"]/df["rating_count"]
df["rating_four_percent"] = df["rating_four_count"]/df["rating_count"]
df["rating_three_percent"] = df["rating_three_count"]/df["rating_count"]
df["rating_two_percent"] = df["rating_two_count"]/df["rating_count"]
df["rating_one_percent"] = df["rating_one_count"]/df["rating_count"]
ratings = [
"rating_five_percent",
"rating_four_percent",
"rating_three_percent",
"rating_two_percent",
"rating_one_percent"
]
for rating in ratings:
df[rating] = df[rating].apply(lambda x: x if x>= 0 and x<= 1 else 0)
# Distribution plot on price
sns.histplot(df['price'])
My output is as follows:
Process finished with exit code 0
so I know there are no errors in the code but I don't see any graphs anywhere as I'm supposed to.
Ive found a way around this by using this at the end
plt.show()
which opens a new tab and uses matplotlib to show me a similar graph.
However in the code I'm using to follow along, matplotlib is not imported or used (I understand that seaborn has built in Matplotlib functionality) as in the plt.show statement is not used but the a visual graph is still achieved.
I've also used print which gives me the following
AxesSubplot(0.125,0.11;0.775x0.77)
Last point to mention is that the code im following along with uses the following
import seaborn as sns
# Distribution plot on price
sns.distplot(df['price'])
but distplot has now depreciated and I've now used histplot because I think that's the best alternative vs using displot, If that's incorrect please let me know.
I feel there is a simple solution as to why I'm not seeing a graph but I'm not sure if it's to do with pycharm or due to something within the code.
matplotlib is a dependency of seaborn. As such, importing matplotlib with import matplotlib.pyplot as plt and calling plt.show() does not add any overhead to your code.
While it is annoying that there is no sns.plt.show() at this time (see this similar question for discussion), I think this is the simplest solution to force plots to show when using PyCharm Community.
Importing matplotlib in this way will not affect how your exercises run as long as you use a namespace like plt.
Be aware the 'data' must be pandas DataFrame object, not: <class 'pandas.core.series.Series'>
I using this, work finely:
# Distribution plot on price
sns.histplot(df[['price']])
plt.show()

Numpy and Matplotlib Error with very Minimal Example

I have been using numpy and matplotlib together for some time now, successfully. Suddenly, I am getting unusual errors when using them together. The following is a minimal example:
import numpy as np
import matplotlib.pyplot as plt
fig,ax = plt.subplots(1,1)
x = np.eye(10)
u = np.linalg.svd(x)
plt.show()
If I run the code once, it works. If I run the code again, I get an exception:
LinAlgError: SVD did not converge. Bizarrely, this behavior disappears when the call to pyplot is removed:
import numpy as np
import matplotlib.pyplot as plt
#fig,ax = plt.subplots(1,1)
x = np.eye(10)
u = np.linalg.svd(x)
#plt.show()
I tried this with two different python environments with numpy versions 18.1 and 18.5. I am wondering if anyone has any information about what could possibly cause this behavior.
edit: I was running these two blocks of code in a jupyter notebook with only those lines of code and nothing else. In order to reproduce the behavior in the interactive interpreter, you need to add the line plt.show() in between runs. I edited the post to include this line.
edit: matplotlib 3.3.2, numpy 18.1 or 18.5, and I can use python 3.8.1 or 3.6.8

Python not showing plots

When I run the following code, plots don't show up even though I am not getting any error messages.
import matplotlib.pyplot as plt
plt.plot = ([1,2], [1,2])
plt.show()
I tried the following
1) Change Spyder->Preferences->Graphics backend = Automatic (Reset kernel)
2)
import matplotlib
matplotlib.use('Agg')
Got error: "no effect because the backend has already been chosen"
I am using Python 3.6 with Spyder that comes with Anaconda
there is an error in your code, it must be:
import matplotlib.pyplot as plt
plt.plot([1,2], [1,2])
plt.show()

Can't use matplotlib.use('Agg'), graphs always show on the screen

I'm studying matplotlib and don't know how to just save the graph and not print it on the screen.
So I've done some research on the Internet, many answers said the solution is matplotlib.use('Agg'). And it must be before importing matplotlib.pyplot or pylab.
Then when I added it in the first line of my script, it doesn't work at all.
import matplotlib
matplotlib.use('Agg')
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
E:\Program Files\Anaconda3\lib\site-packages\matplotlib\__init__.py:1401: UserWarning: This call to matplotlib.use() has no effect
because the backend has already been chosen;
matplotlib.use() must be called *before* pylab, matplotlib.pyplot,
or matplotlib.backends is imported for the first time.
warnings.warn(_use_error_msg)
I use Anaconda Spyder, so I restarted kernel and ran my script again, I got same wrong information.
Then I restarted kernel again and directly typed the following code in the console:
In[1]: import matplotlib as mpl
In[2]: mpl.use('Agg')
E:\Program Files\Anaconda3\lib\site-packages\matplotlib\__init__.py:1401: UserWarning: This call to matplotlib.use() has no effect
because the backend has already been chosen;
matplotlib.use() must be called *before* pylab, matplotlib.pyplot,
or matplotlib.backends is imported for the first time.
warnings.warn(_use_error_msg)
Also, if I delete 'plt.show()' at the end of script or add 'plt.ioff()', the graph will always print on the screen.
Thanks for everyone's answer. Now I have two solutions:
just use plt.close() , this will not change the backend and the figure doesn't show up.
use plt.switch_backend('Agg'), this will switch the backend to 'agg' and no figure printed on the screen.
You can try to switch the backend. Apparently Spyder loads matplotlib before you do, and use has no effect. This may be helpful:
How to switch backends in matplotlib / Python
The answer to your original question is simple.
If you don't want to show the graph on screen, just don't use plt.show()
So what you've gotta do is simply:
import matplotlib.pylab as plt
plt.plot(x,y) #whatever the x, y data be
#plt.show() """Important: either comment this line or delete it"""
plt.savefig('path/where/you/want/to/save/filename.ext')
#'filename' is either a new file or an already existing one which will get overwritten at the time of execution. 'ext' can be any valid image format including jpg, png, pdf, etc.
plt.plot(x,y)
plt.savefig('path/figure_filename.jpg',dpi=300)

Use pylab to plot image returned from Scipy

I'm working to migrate from MatLab to python in Sage.
So I use these commands and I faced this error in Sage:
from scipy import misc
l = misc.lena();
import pylab as pl
pl.imshow(l)
The Error or message (i don't know) is:
matplotlib.image.AxesImage object at 0xb80198c
And it doesn't show any image
It's not an error, just print the object that method returned.
There are two ways to show the figure:
Add pl.show() after calling pl.imshow(l)
Use ipython --pylab to open your python shell,
That is an object being returned from pylab after using the "imshow" command. That is the location of the Axes image object.
documentation:
http://matplotlib.sourceforge.net/api/pyplot_api.html#matplotlib.pyplot.imshow
Looks like it says it displays the object to the current axes. If you havent already created a plot I imagine you wont see anything
Simple google search suggests this might be what you are looking for
http://docs.scipy.org/doc/scipy/reference/generated/scipy.misc.lena.html
from scipy import misc
l = misc.lena();
import pylab as pl
pl.imshow(l)
####use this
pl.show()

Categories