Python codes using numpy and matplotlib without outputting result - python

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!

Related

AttributeError: module 'matplotlib' has no attribute 'bar'

I am using python 3.6 and am a learner. Below is a simple code of a sin wave.
import numpy as np
import pandas as pd
import matplotlib as plt
import seaborn as sb
smartphone = pd.read_csv("C://Users/Admin/smartphones.csv")
count = smartphone.Ram.value_counts()
category = count.index
plt.bar(category,count)
plt.xlable('Ram')
plt.ylable('Count')
plt.xticks([1,2,3,4])
plt.yticks([1,2,3])
plt.show()`
I am receiving the error "AttributeError: module 'matplotlib' has no attribute 'bar'" Any help would be appreciated.
When you see other people's code and they have plt.bar(x,y) or plt.show() the plt they are referring to is a sub-module of the matplotlib package called pyplot.
So this is really what's going on:
import matplotlib
matplotlib.pyplot.bar(count, category)
...
...
...
matplotlib.pyplot.show()
So if you are mainly using pyplot what you want to do at the top of your script is,
import matplotlib.pyplot as plt
Then you can just:
plt.bar(count,category)
...
...
...
plt.show()
edit: Also just wanted to add, that I think you have a typo and have xlable and ylable, but it should be xlabel and ylabel. Your code will throw errors if you don't fix that.
Try using import matplotlib.pyplot as plt instead of import matplotlib as plt.

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

How do I use the detrending function for matplotlib.pyplot.acorr?

I am a Python beginner. I am trying to detrend a time-series before running an autocorrelation analysis by using acorr in matplotlib. But there is something about the syntax that I fail understand.
Matplotlib's website (https://matplotlib.org/3.1.0/api/_as_gen/matplotlib.pyplot.acorr.html) describes how to use detrending with the acorr function: "x is detrended by the detrend callable. This must be a function x = detrend(x) accepting and returning an numpy.array." I must be reading this wrong, because the code I use does not work.
Failed attempts:
plt.acorr(values, detrend=True)
plt.acorr(values, detrend="linear")
plt.acorr(values=detrend(values))
As you can see, some rudimentary fact about syntax or matplotlib escapes me. Please help.
In matplotlib.mlab you find functions which you can use for detrending. An example:
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import mlab
wn = np.random.normal(size=10**3)
plt.figure()
plt.acorr(np.abs(wn), maxlags=200, detrend=mlab.detrend_none) #default detrend
plt.figure()
plt.acorr(np.abs(wn), maxlags=200, detrend=mlab.detrend) #subtract sample mean

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