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.
Related
I'm trying to run the code below, but I keep getting the same error : "ModuleNotFoundError: No module named 'basic_units'".
import sympy as sym
import math
import numpy as np
import os
import matplotlib.pyplot as plt
from basic_units import radians
fig, ax = plt.subplots(subplot_kw={'projection': 'polar'})
ax.plot([np.pi, np.pi], [0, 10], xunits=radians)
plt.show()
I've seen that used in other code, but I just can't get it to work.
I was trying to make a polar plot with the angles in radians, and this seemed to be the only solution I could find, so I tried to run this test, but I encountered this error
basic_units is not a python package, you should have a look for official matplotlib document:
Radian ticks#
Plot with radians from the basic_units mockup example package.
This example shows how the unit class can determine the tick locating,
formatting and axis labeling.
This example requires basic_units.py
import matplotlib.pyplot as plt
import numpy as np
from basic_units import radians, degrees, cos
You could download above source code & put in your project.
Did you download basic_units.py file as numpy documentation mentions (https://matplotlib.org/stable/gallery/units/radian_demo.html)? If yes, you have to provide a valid path in the import statement. Now you're trying to import it as a module, but it should be a file. Like:
from .basic_units import radians
or
from my_code.src.basic_units import radians
I need to include Python code chunks in an R Markdown HTML. However, when I do so, the plot doesn't show up.
This is the code chunk I have which want to implement. I know this works in Python.
```{python, results='asis'}
import numpy as np
import matplotlib.pyplot as plt
import numpy.random as rng
import matplotlib.cm as cm
from matplotlib.animation import FuncAnimation
radii=(rng.random(int(1e3))+1)**2
iota=2*np.pi*rng.random(int(1e3))
x_posit=np.sqrt(radii)*np.cos(iota)
y_posit=np.sqrt(radii)*np.sin(iota)
plt.plot(x_posit, y_posit, 'go')
```
I expect to get a plot like this
But instead I get this, that is no graph in the R markdown Document. I'm knitting to HTML
Install the library reticulate via install.packages("reticulate") and load this chunk before your code presented above:
```{r setup, include=FALSE}
library(knitr)
library(reticulate)
knitr::knit_engines$set(python = reticulate::eng_python)
```
```{python}
import numpy as np
import matplotlib.pyplot as plt
import numpy.random as rng
import matplotlib.cm as cm
from matplotlib.animation import FuncAnimation
radii=(rng.random(int(1e3))+1)**2
iota=2*np.pi*rng.random(int(1e3))
x_posit=np.sqrt(radii)*np.cos(iota)
y_posit=np.sqrt(radii)*np.sin(iota)
plt.plot(x_posit, y_posit, 'go')
plt.show()
```
Note the plt.show() command.
This will produce your expected output!
Exactly how J_F above described. Just as a reminder: In case you have more than one Python version on your system e.g. Mac with Python 2.7 and 3.x.
```{r setup, include=FALSE}
Library(knitr)
Library(reticulate)
knitr::knit_engines$set(python3 = reticulate::eng_python)
```
```{python3}
enter code here
```
I am trying to learn how to use basemap in python. I used the following site for learning http://www.datadependence.com/2016/06/creating-map-visualisations-in-python/.
but when I typed the following
import matplotlib.pyplot as plt
import matplotlib.cm
import basemap
fig,ax=plt.subplots(figsize=(10,20))
m=basemap(resolution='c',projection='merc',lat_0=54.5,lon_0=-4.36,llcrnrlon=-6.,llcrnrlat=49.5,urcrnrlon=2.,urcrnrlat=55.2)
m.drawmapboundary(fill_color='#46bcec')
m.fillcontinents(color='#f2f2f2',lake_color='#46bcec')
m.drawcoastlines()
I get an error as TypeError: 'module' object is not callable. Why is the reason for this?
You misunderstood the example code. You have to write:
from mpl_toolkits.basemap import Basemap
m=Basemap(resolution='c',projection='merc',lat_0=54.5,lon_0=-4.36,llcrnrlon=-6.,llcrnrlat=49.5,urcrnrlon=2.,urcrnrlat=55.2)
Basemap have to be start from capital letter. It is very important for Python. Python is case sensitivity language.
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!
I searched many posts, but they don't seem to be helpful.
In folder dir1/ I have main.py and plotcluster.py. In plotcluster.py I have:
import matplotlib as plt
import itertools as it
....
def plotc():
colors = it.cycle('ybmgk')
....
plt.figure()
....
In main.py, I use plotcluster.py:
import plotcluster as plc
....
plc.plotc()
But this gives me a error saying module object is not callable.
20 linestyles = it.cycle('-:_')
21
---> 22 plt.figure()
23 # plot the most frequent ones first
24 for iter_count, (i, _) in enumerate(Counter(centerid).most_common()):
TypeError: 'module' object is not callable
It doesn't complaint about the itertools module, but the plt one bothers it. This makes me so confusing!
any help will be appreciated !! Thanks in advance!
#suhail 's answer will work. Essentially you were accessing matplotlib.figure which is the module. Also I think you are trying to access the pyplot functions (gen that is imported as plt) and its enough to import that module to access most of the standard plotting api's.
So in your plotcluster.py change the first line to
import matplotlib.pyplot as plt
It should be smooth sailing from there on and you can use stuff like
plt.plot(), plt.show() and so on.
try
plt.figure.Figure()
not
plt.figure