matplotlib plotting multiple lines [duplicate] - python

X = (6 * np.random.rand(10, 1) - 3)
y_cap = (0.44530754 * X**2)+(1.01366334 * X)+0.13309963
plt.plot(X, y_cap, ls = '--')
I'm solving a polynomial regression problem (degree=2). I got the coefficients of X, X^2, and performed the polynominal regression. And now when I tried to plot using the above code I got these lines instead of a curve. How to solve this?

This happens because your X values are not ordered. Just do this before calculating y_cap:
X = np.sort(X, 0)
Then it will work. Full example:
import numpy as np
import matplotlib.pyplot as plt
X = (6 * np.random.rand(10, 1) - 3)
X = np.sort(X, 0)
y_cap = (0.44530754 * X**2)+(1.01366334 * X)+0.13309963
plt.plot(X, y_cap, ls = '--')
plt.show()

Related

How build two graphs in one figure, module Matplotlib [duplicate]

This question already has answers here:
How to plot multiple functions on the same figure, in Matplotlib?
(4 answers)
Closed 1 year ago.
How to build two graphs in one figure from the equations below
y = (x+2)^2
y = sin(x/2)^2
There is my code:
import matplotlib.pyplot as plt
import numpy as np
from math import sin
y = lambda x: sin(x / 2) ** 2
y1 = lambda x: (x + 2) ** 2
fig = plt.subplots()
x = np.linspace(-3, 3, 100)
plt.plot(x, y(x))
plt.plot(x, y1(x))
plt.show()
Use supplots to make 2 Axes in your Figure:
import matplotlib.pyplot as plt
import numpy as np
fig, (ax1,ax2) = plt.subplots(nrows=2)
x = np.linspace(-3, 3, 100)
ax1.plot(x, np.sin(x / 2) ** 2)
ax2.plot(x, (x + 2) ** 2)

How can I plot x**2 + y**2 = 9 as a circle not 3d equation in python [duplicate]

This question already has answers here:
Is it possible to plot implicit equations using Matplotlib?
(6 answers)
Closed 1 year ago.
How can I plot x^2 + y^2 = 9 as a circle not 3d equation in python
I cannot find any where to plot equality equation in python. Can you please help me out in this.
You can use sympy as follows:
from sympy import Eq, plot_implicit
from sympy.abc import x, y
plot_implicit(Eq(x ** 2 + y ** 2, 9), aspect_ratio=(1, 1))
There is also plot_parametric:
from sympy import plot_parametric, cos, sin, pi
from sympy.abc import t
plot_parametric(cos(t), sin(t), (t, 0, 2 * pi), aspect_ratio=(1, 1))
You can derive x,y by solving the equation.
For example, noting that -3 <= x <= 3 and y = +- sqrt(9-x^2),
import numpy as np
x = np.linspace(-3, 3)
y = np.sqrt(9-x)
import matplotlib.pyplot as plt
plt.scatter(x, y)
plt.scatter(x, -y)
Alternatively, since this relation can be expressed by the polar coordinate 0 <= theta < 2*pi with x = 3 cos(theta), y = 3 sin(theta),
theta = np.linspace(0, 2*np.pi)
x = 3*np.cos(theta)
y = 3*np.sin(theta)
plt.scatter(x, y)

How to avoid zigzag lines in matplotlib pyplot.plot?

X = (6 * np.random.rand(10, 1) - 3)
y_cap = (0.44530754 * X**2)+(1.01366334 * X)+0.13309963
plt.plot(X, y_cap, ls = '--')
I'm solving a polynomial regression problem (degree=2). I got the coefficients of X, X^2, and performed the polynominal regression. And now when I tried to plot using the above code I got these lines instead of a curve. How to solve this?
This happens because your X values are not ordered. Just do this before calculating y_cap:
X = np.sort(X, 0)
Then it will work. Full example:
import numpy as np
import matplotlib.pyplot as plt
X = (6 * np.random.rand(10, 1) - 3)
X = np.sort(X, 0)
y_cap = (0.44530754 * X**2)+(1.01366334 * X)+0.13309963
plt.plot(X, y_cap, ls = '--')
plt.show()

Add color to line plot in matplotlib depending on given values [duplicate]

This question already has answers here:
How to plot a gradient color line in matplotlib?
(7 answers)
Closed 3 years ago.
So I have a normal scatter plot:
import numpy as np
import matplotlib.pyplot as plt
import random
x = np.random.random_sample((100,))
x = np.sort(x)
y = x + np.sin(np.pi * x)
z = 5 * x
fig = plt.figure()
plot = plt.scatter(x, y, s= 10, c = z, cmap='coolwarm')
fig.colorbar(plot)
plt.grid(True, 'both')
plt.show()
that produces a plot something like this
However, I would really like to add a line to scatter and connect these points. It may sound ridiculous since it is easy to follow the points in given case, but imagine if the data would be more scattered and possibly multiple datasets ...
So my goal is to add a line to the scatter above, but the color of the line should change according to value of 'z', the same way scatter plot does. Is that even possible?
EDIT:
The x, y, z provided above is just random data to explain the problem. In reality, you can imagine the points (x, y) coordinates are given from an experiment meaning in general there is no relation between x, y, z or even if it is, it is NOT known upfront.
You can add another scatterplot using np.linspace() function:
import numpy as np
import matplotlib.pyplot as plt
import random
x = np.random.random_sample((100,))
x = np.sort(x)
y = x + np.sin(np.pi * x)
z = 5 * x
fig = plt.figure()
plot = plt.scatter(x, y, s= 10, c = z, cmap='coolwarm')
fig.colorbar(plot)
plt.grid(True, 'both')
# add another scatterplot
x_line = np.linspace(np.min(x), np.max(x), num=1000)
y_line = x_line + np.sin(np.pi * x_line)
z_line = 5 * x_line
plt.scatter(x_line, y_line, c=z_line, s=0.1, cmap='coolwarm')
plt.show()

Determine plot smoothing by a parameter

I want to create a plot showing both the real data and a smoothed version of the data. Now, I am using the following script:
import pandas as pd
import matplotlib.pyplot as plt
# DataFrame of 321 values
df = pd.read_csv('data.csv')
r = df.rolling(window=10, center=True, on='Value').mean()
fig = plt.figure()
ax = df['Value'].plot(style='--', c='b', alpha=0.5)
r.plot(ax=ax, legend=0, c='b')
plt.show()
However, I would like this to work similarly to e.g. TensorBoard. There, you specify a smoothing parameter between 0 and 1 which changes the window of the rolling mean, 0 being no smoothing and 1 being extreme smoothing. How is this done? Can I also do this in Python?
It seems that you can use scipy.interpolate package to add smoothness to your data, something like this:
from scipy.interpolate import spline
# 300 represents number of points to make between T.min and T.max
# you can use other number to adjust smoothness
axnew = np.linspace(df['Value'].min(), df['Value'].max(), 300)
power_smooth = spline(df['Value'], df['y_Value'], axnew)
plt.plot(xnew, power_smooth)
plt.show()
Sample from docs:
Cubic-spline
>>> x = np.arange(0, 2 * np.pi + np.pi / 4, 2 * np.pi / 8)
>>> y = np.sin(x)
# s parameter for adjust the smoothness
>>> tck = interpolate.splrep(x, y, s=0)
>>> xnew = np.arange(0, 2 * np.pi, np.pi / 50)
>>> ynew = interpolate.splev(xnew, tck, der=0)
Related question: Plot smooth line with PyPlot
Update: #ImportanceOfBeingErnest noticed that spline is depreciated in the newest version of scipy, so you should investigate the splev and splrep. Some samples can be found here.

Categories