how can I fix my histogram plot - python

I want to plot a very simple histogram diagram with python. Here is my code :
from numpy import *
from matplotlib.pyplot import*
from random import*
nums = []
N = 10
for i in range(N):
a = randint(0,10)
nums.append(a)
bars= [0,1,2,3,4,5,6,7,8,9]
hist(nums)
show()
This is the result
How can I put the bars just in the integer place? Why does my diagram show the float numbers too?

you make bars but then don't use it. If you set the bins option of hist to bars, it all works fine
bars= [0,1,2,3,4,5,6,7,8,9]
hist(nums,bins=bars)
To set the yticks to only integer values, you can use a MultipleLocator from the matplotlib.ticker module:
from numpy import *
from matplotlib.pyplot import*
import matplotlib.ticker as ticker
from random import*
nums = []
N = 10
for i in range(N):
a = randint(0,10)
nums.append(a)
bars= [0,1,2,3,4,5,6,7,8,9]
hist(nums,bins=bars)
gca().yaxis.set_major_locator(ticker.MultipleLocator(1))
show()

Related

Point deviding by line with matplotlib

I made 30 random points using np.random.uniform.
And i want these points to be divided by random line like the picture below.
Could you give me some codes or advice??
Making points is easy but dividing is difficult ..
Code is like this
import numpy as np
import matplotlib
import matplotlib.pyplot as plt
import random
import math
m=np.random.uniform(-10,10,30)
n=np.random.uniform(-10,10,30)
a=random.randrange(-5,5)
b=random.randrange(-10,10)
x= np.array(range(-10,20))
y=a*x+b
plt.plot(x,y)
plt.scatter(m,n)
plt.xlim(-10,10)
plt.ylim(-10,10)
plt.show()
enter image description here
I want to devide points by the line like this
enter image description here
I feel like using for loop is possible but I don't know how. Could you give me some advice??
I think you can use the filter function to divide the points into two parts.
The code is Here.
import numpy as np
import matplotlib.pyplot as plt
import random
m=np.random.uniform(-10,10,30)
n=np.random.uniform(-10,10,30)
a=random.randrange(-5,5)
b=random.randrange(-10,10)
x= np.array(range(-10,20))
y=a*x+b
plt.plot(x,y)
# above
result = list(filter(lambda item: item[1] >= a*item[0]+b, zip(m,n)))
xa, ya = list(zip(*result))
plt.scatter(xa,ya,color = "r",marker="*")
# below
result = list(filter(lambda item: item[1] < a*item[0]+b, zip(m,n)))
xb, yb = list(zip(*result))
plt.scatter(xb,yb, marker="^",color="b")
plt.xlim(-10,10)
plt.ylim(-10,10)
plt.show()

I am not able to display graph in matplotlib

I'm trying to print a logistic differential equation and I'm pretty sure the equation is written correctly but my graph doesn't display anything.
import matplotlib as mpl
import matplotlib.pyplot as plt
import numpy as np
def eq(con,x):
return con*x*(1-x)
xList = np.linspace(0,4, num=1000)
con = 2.6
x= .4
for num in range(len(xList)-1):
plt.plot(xList[num], eq(con,x))
x=eq(con,x)
plt.xlabel('Time')
plt.ylabel('Population')
plt.title("Logistic Differential Equation")
plt.show()
You get nothing in your plot because you are plotting points.
In plt you need to have x array and y array (that have the same length) in order to make a plot.
If you want to do exactly what you are doing I suggest to do like this:
import matplotlyb.pyplot as plt # just plt is sufficent
import numpy as np
def eq(con,x):
return con*x*(1-x)
xList = np.linspace(0,4, num=1000)
con = 2.6
x= .4
y = np.zeros(len(xList)) # initialize an array with the same lenght as xList
for num in range(len(xList)-1):
y[num] = eq(con,x)
x=eq(con,x)
plt.figure() # A good habit is always to use figures in plt
plt.plot(xList, y) # 2 arrays of the same lenght
plt.xlabel('Time')
plt.ylabel('Population')
plt.title("Logistic Differential Equation")
plt.show() # now you should get somthing here
I hope that this helps you ^^

how to plot some lists with different shape?

I have some lists that each of which has a different shape and I would like to plot all of them together in one polar scatter plot. I also tried to use iter tools but I could not find the solution.
import numpy as np
import matplotlib.pyplot as plt
a1=[1,2,3,4,5,6]
a2=[2,3,5,6]
a3=[1,2,3]
a4=[1,2,3,4,4,56,7,8]
ax1 = plt.subplot(111,polar= True)
for i in range (0,3):
theta = 4 * np.pi * np.random.rand(len(a[i]))
ax1.set_ylim(0,0.1)
ax1.set_rlabel_position(180)
for i in range (0,3):
ax1.scatter(theta,a[i], cmap='hsv', alpha=0.5)
Be carefull i modified your lists for a better visual exmaple!
I hope I understood your question correctly...
import numpy as np
import matplotlib.pyplot as plt
a1=[1,2,3,4,5,6]
a2=[2,3,5,6]
a3=[1,2,3]
a4=[1,2,3,4,4,7,7,8]
ax1 = plt.subplot(111,polar= True)
for onelist in [a1,a2,a3,a4]:
theta_list = np.linspace(0,2*np.pi,len(onelist))
ax1.plot(theta_list,onelist,marker="x")
plt.show()

Plotting exponential function

I'm relatively new to Python.
I'm trying to plot exponential term value ranging between 0 and 100.
There is no error indicated with the code but the Plot has no legend(line).
Kindly help me.
Thank you.
import math
import matplotlib.pyplot as plt
for i in range (0,101):
m = math.exp(i)
print("For i = ",i)
print("(e^i) = ",m)
plt.plot(i,m,'b--',linewidth=3)
plt.ylabel('e^i')
plt.xlabel('i')
plt.show()
You can change your code in this way:
import math
import matplotlib.pyplot as plt
l = list(range (0,101))
m_l = []
for i in l:
m = math.exp(i)
print("For i = ",i)
print("(e^i) = ",m)
m_l.append(m)
plt.plot(l,m_l,'b--',linewidth=3)
plt.ylabel('e^i')
plt.xlabel('i')
plt.legend(['m_l'])
plt.show()
With your code, you were plotting just the last values of i and m

pyplot: loglog() with base e

Python (and matplotlib) newbie here coming over from R, so I hope this question is not too idiotic. I'm trying to make a loglog plot on a natural log scale. But after some googling I cannot somehow figure out how to force pyplot to use a base e scale on the axes. The code I have currently:
import matplotlib.pyplot as pyplot
import math
e = math.exp(1)
pyplot.loglog(range(1,len(degrees)+1),degrees,'o',basex=e,basey=e)
Where degrees is a vector of counts at each value of range(1,len(degrees)+1). For some reason when I run this code, pyplot keeps giving me a plot with powers of 2 on the axes. I feel like this ought to be easy, but I'm stumped...
Any advice is greatly appreciated!
When plotting using plt.loglog you can pass the keyword arguments basex and basey as shown below.
From numpy you can get the e constant with numpy.e (or np.e if you import numpy as np)
import numpy as np
import matplotlib.pyplot as plt
# Generate some data.
x = np.linspace(0, 2, 1000)
y = x**np.e
plt.loglog(x,y, basex=np.e, basey=np.e)
plt.show()
Edit
Additionally if you want pretty looking ticks you can use matplotlib.ticker to choose the format of your ticks, an example of which is given below.
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.ticker as mtick
x = np.linspace(1, 4, 1000)
y = x**3
fig, ax = plt.subplots()
ax.loglog(x,y, basex=np.e, basey=np.e)
def ticks(y, pos):
return r'$e^{:.0f}$'.format(np.log(y))
ax.xaxis.set_major_formatter(mtick.FuncFormatter(ticks))
ax.yaxis.set_major_formatter(mtick.FuncFormatter(ticks))
plt.show()
It can also works for semilogx and semilogy to show them in e and also change their name.
import matplotlib.ticker as mtick
fig, ax = plt.subplots()
def ticks(y, pos):
return r'$e^{:.0f}$'.format(np.log(y))
plt.semilogy(Time_Series, California_Pervalence ,'gray', basey=np.e )
ax.yaxis.set_major_formatter(mtick.FuncFormatter(ticks))
plt.show()
Take a look at the image.

Categories