Numpy and Matplotlib Error with very Minimal Example - python

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

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

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

Flushing and updating a graph in matlibplot via X11 backend

I'm trying to print a graph from a Python script on AWS Linux over SSH/Xming on my Windows machine. Everything works nicely if I use a blocking plt.show() - I can't, however, show the graph correctly when running in a loop without blocking. My sample code is:
import matplotlib
matplotlib.use('Agg')
import seaborn as sns
import matplotlib.pyplot as plt
import time
import pandas as pd
import numpy as np
df = pd.DataFrame(np.random.randn(100, 4), columns=list('ABCD'))
while True:
heatmap = sns.heatmap(df)
plt.show(block=False)
time.sleep(10)
This setup (without the first two lines) works smoothly in Windows with Anaconda and IPyhon - I get an alternating plot and sleep. I'm getting no output this way with Linux though.

Python codes using numpy and matplotlib without outputting result

I just started learning doing financial analytics with python today. I ran into a block of code and it requires importing numpy and matplotlib to run the codes and generate a graph(not sure if it really can).
The codes are like this:
import numpy as np
import matplotlib as mpl
import matplotlib.pyplot as plt
mpl.rcParams['font.family'] = 'serif'
K = 8000
S = np.linspace(7000,9000,100)
h = np.maximum(S-K, 0)
plt.figure()
plt.plot(S, h, lw=2.5)
plt.xlabel('index level $S-t$ at maturity')
plt.ylabel("inner value of European call option")
plt.grid(True)
I installed both numpy and matplotlib but after I tried running the codes nothing came out.
I really don't know what went wrong. This is my first time using numpy and matplotlib and I have not idea how to solve this problem.
Please help!

numpy and matplotlib entry point error in anaconda windows 64 bit

import numpy as np
import matplotlib.pyplot as plt
x = [2,3,4,5,7,9,13,15,17]
plt.plot(x)
plt.ylabel('Sunlight')
plt.xlabel('Time')
plt.show()
while executing this in anaconda I got the error
Entry Point Not Found:"The procedure entry point
mkl_aa_fw_get_max_memory could not be located in the dynamic link
library mkl_core.dll"
Can anyone please tell how to resolve the issue

Categories