How to draw a graph using matplotlib? - python-3.x

draw a graph of equation in the form of y=mx+b in python3.x
example y = 5x + 9

This is a very general question. Try to be more specific. It depends how you want to draw it.
import numpy as np
import matplotlib.pyplot as plt
x = np.arange(0., 5., 0.2)
y = 5 * x + 9
plt.plot(x, y)
plt.show()
or
import numpy as np
import matplotlib.pyplot as plt
x = np.arange(-1., 5., 0.2)
y = 5 * x + 9
fig, ax = plt.subplots()
ax.plot(x,y)
ax.grid(True, which='both')
ax.axhline(y=0, color='k')
ax.axvline(x=0, color='k')
These are very basic drawing. You can create more sophisticated graphs, but you will have to be more specific in your question.

You can define your y(x) function and then plot it as follows:
import matplotlib.pyplot as plt
def y(x):
return [5*i+9 for i in x]
x = range(0,10)
plt.plot(x,y(x))
plt.show()
This produces follwing graph:
With turtle
You can as well get a graph with turtle with following code for example:
from turtle import Turtle, Screen
def y(x):
return 5*x+9
def plotter(turtle, x_range):
turtle.penup()
for x in x_range:
turtle.goto(x, y(x))
turtle.pendown()
screen = Screen()
screen.setworldcoordinates(0, 0, 9, 60)
turtle = Turtle(visible=False)
x = range(0,10)
plotter(turtle, x)
screen.exitonclick()
Which produces:

Related

Plotting colorbar in Python 3

I am trying to color the errorbar points based on the color from an array. But getting an error. My code is shown below:
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.cm import ScalarMappable, coolwarm as cmap
from matplotlib.colors import Normalize
fig = plt.figure(1)
sp = fig.add_subplot(1, 1, 1)
sp.set_xlabel(r'$x$')
sp.set_ylabel(r'$y$')
x = np.random.rand(10)
y = np.random.rand(10)
M = np.logspace(9, 10, 10)
norm = Normalize(vmin=8, vmax=11,clip=False) # controls the min and max of the colorbar
smap = ScalarMappable(cmap=cmap, norm=norm)
for xi, yi, Mi in zip(x, y, M):
c = cmap(norm(np.log10(Mi))) # make sure to color by log of mass, not mass
sp.errorbar(
xi,
yi,
yerr=[[.1], [.1]],
xerr=[[.1], [.1]],
ecolor=c,
marker='o',
mec=c,
mfc=c
)
cb = plt.colorbar(smap)
cb.set_label(r'$\log_{10}M$')
I am getting the following error:
TypeError: You must first set_array for mappable
For matplotlib < 3.1, you need to set an array - which can be empty
sm = ScalarMappable(cmap=cmap, norm=norm)
sm.set_array([])
fig.colorbar(sm)
For matplotlib >= 3.1, this is not necessary any more.
sm = ScalarMappable(cmap=cmap, norm=norm)
fig.colorbar(sm)

Matplotlib 3d - setting ticks for another axis

How to set ticks to be on the opposite axes please? When I drop it the axes changes but not in this way. Thank you
import matplotlib as mpl
from mpl_toolkits.mplot3d import Axes3D
import numpy as np
import matplotlib.pyplot as plt
mpl.rcParams['legend.fontsize'] = 10
fig = plt.figure()
ax = fig.gca(projection='3d')
theta = np.linspace(-4 * np.pi, 4 * np.pi, 100)
z = np.linspace(-2, 2, 100)
r = z**2 + 1
x = r * np.sin(theta)
y = r * np.cos(theta)
ax.plot(x, y, z, label='parametric curve')
ax.legend()
plt.show()

Can't plot anything with matplotlib

Whenever I try to plot something with matplotlib, I get the following error:
File "C:\Users\username\AppData\Local\Programs\Python\Python37-32\Lib\tkinter\__init__.py", line 2018, in __init__
baseName = os.path.basename(sys.argv[0])
builtins.IndexError: list index out of range
For example, i've tried the following code:
import matplotlib.pyplot as plt
import numpy as np
N = 50
x = np.random.rand(N)
y = np.random.rand(N)
colors = np.random.rand(N)
area = np.pi * (15 * np.random.rand(N))**2 # 0 to 15 point radii
plt.scatter(x, y, s=area, c=colors, alpha=0.5)
plt.show()
I have the latest version of matplotlib, please help.
Thank you
You need to import numpy.
import numpy as np
import matplotlib.pyplot as plt
N = 50
x = np.random.rand(N)
y = np.random.rand(N)
colors = np.random.rand(N)
area = np.pi * (15 * np.random.rand(N))**2 # 0 to 15 point radii
plt.scatter(x, y, s=area, c=colors, alpha=0.5)
plt.show()

Using scipy's solve_ivp to solve non linear pendulum motion

I am still trying to understand how solve_ivp works against odeint, but just as I was getting the hang of it something happened.
I am trying to solve for the motion of a non linear pendulum. With odeint, everything works like a charm, on solve_ivp hoever something weird happens:
import numpy as np
from matplotlib import pyplot as plt
from scipy.integrate import solve_ivp, odeint
g = 9.81
l = 0.1
def f(t, r):
omega = r[0]
theta = r[1]
return np.array([-g / l * np.sin(theta), omega])
time = np.linspace(0, 10, 1000)
init_r = [0, np.radians(179)]
results = solve_ivp(f, (0, 10), init_r, method="RK45", t_eval=time) #??????
cenas = odeint(f, init_r, time, tfirst=True)
fig = plt.figure()
ax1 = fig.add_subplot(111)
ax1.plot(results.t, results.y[1])
ax1.plot(time, cenas[:, 1])
plt.show()
What am I missing?
It is a numerical problem. The default relative and absolute tolerances of solve_ivp are 1e-3 and 1e-6, respectively. For many problems, these values are too big, and tighter error tolerances should be given. The default relative tolerance for odeint is 1.49e-8.
If you add the argument rtol=1e-8 to the solve_ivp call, the plots agree:
import numpy as np
from matplotlib import pyplot as plt
from scipy.integrate import solve_ivp, odeint
g = 9.81
l = 0.1
def f(t, r):
omega = r[0]
theta = r[1]
return np.array([-g / l * np.sin(theta), omega])
time = np.linspace(0, 10, 1000)
init_r = [0, np.radians(179)]
results = solve_ivp(f, (0, 10), init_r, method='RK45', t_eval=time, rtol=1e-8)
cenas = odeint(f, init_r, time, tfirst=True)
fig = plt.figure()
ax1 = fig.add_subplot(111)
ax1.plot(results.t, results.y[1])
ax1.plot(time, cenas[:, 1])
plt.show()
Plot:

matplotlib: put two x-y plots in one

I am using the following codes to plot several data points (xi, yi)
import numpy as np
import matplotlib.pyplot as plt
xi = np.array(data_df[['col_A']])
yi = np.array(data_df[['col_B']])
plt.figure()
plt.plot(xi, yi)
x = np.linspace(0, 30, 30)
y= np.exp(x*0.16)
plt.plot(x, y)
plt.show()
I want the plot to look like this:
Thanks!
User subplots to plot more than 1 plots in 1 figure.You need to call plt.show() only once.
import numpy as np
import matplotlib.pyplot as plt
xi = np.array(data_df[['col_A']])
yi = np.array(data_df[['col_B']])
plt.figure()
plt.subplot(2,1,1)
plt.plot(xi, yi)
plt.subplot(2,1,2)
x = np.linspace(0, 30, 30)
y= np.exp(x*0.16)
plt.plot(x, y)
plt.show()

Resources