Fill area between two functions - python

import matplotlib.pyplot as plt
import numpy as np
def domain():
x = np.arange(0, 10, 0.001)
f1 = lambda x: (2*x - x**2)**0.5
plt.plot(x, f1(x), label = '$y = \sqrt{2x - x^2}$')
plt.plot(f1(x), x, label = '$x = \sqrt{2y - y^2}$')
plt.xlabel('X')
plt.ylabel('Y')
plt.legend(loc='best')
axes = plt.gca()
axes.set_xlim([0, 5])
axes.set_ylim([0, 5])
plt.show()
domain()
How can I make use of the fill_between() to fill the area between the 2 lines? In other words, how can I fill the small flower petal between the green and blue lines?

#user 5061 was right on the code, inverse function was off there
import matplotlib.pyplot as plt
import numpy as np
def domain():
x = np.arange(0, 10, 0.001)
f1 = lambda x: (2*x - x**2)**0.5
f2 = lambda x: 1 - (1-x*x)**0.5 # other part is f2 = lambda x: 1 + (1-x*x)**0.5
plt.plot(x, f1(x), label = '$y = \sqrt{2x - x^2}$')
plt.plot(f1(x), x, label = '$x = \sqrt{2y - y^2}$')
plt.fill_between(x, f1(x), f2(x), where=f1(x)>=f2(x), interpolate=True, color='yellow')
plt.xlabel('X')
plt.ylabel('Y')
plt.legend(loc='best')
axes = plt.gca()
axes.set_xlim([0, 5])
axes.set_ylim([0, 5])
plt.show()
domain()
Not taking the positive component 1 + (1-x*x)**0.5 since it doesn't affect the intersection.

You can use fill_between() and fill between your two lines when a condition is met.
(I altered a bit your code, since the way you wrote it i had to find the inverse function of f1)
import matplotlib.pyplot as plt
import numpy as np
def domain():
x = np.arange(0, 2, 0.001)
f = lambda x: x**0.5
g = lambda x: x**2
plt.plot(x, f(x), label = '$y = \sqrt{2x - x^2}$')
plt.plot(x, g(x), label = '$x = \sqrt{2y - y^2}$')
plt.xlabel('X')
plt.ylabel('Y')
plt.legend(loc='best')
plt.fill_between(x, f(x), g(x),where=f(x) > g(x))
axes = plt.gca()
axes.set_xlim([0, 2])
axes.set_ylim([0, 2])
plt.show()
domain()

Related

Gradient 2D plot using contourf

I did a test code brigging something I saw on stack on different topic, and try to assemble it to make what I need : a filled curve with gradient.
After validate this test code I will make a subplot (4 plots for 4 weeks) with the same min/max for all plot (it's a power consumption).
My code :
from matplotlib import pyplot as plt
import numpy as np
# random x
x = range(100)
# smooth random y
y = 0
result = []
for _ in x:
result.append(y)
y += np.random.normal(loc=0, scale=1)#, size=len(x))
y = result
y = list(map(abs, y))
# creation of z for contour
z1 = min(y)
z3 = max(y)/(len(x)+1)
z2 = max(y)-z3
z = [[z] * len(x) for z in np.arange(z1,z2,z3)]
num_bars = len(x) # more bars = smoother gradient
# plt.contourf(x, y, z, num_bars, cmap='greys')
plt.contourf(x, y, z, num_bars, cmap='cool', levels=101)
background_color = 'w'
plt.fill_between(
x,
y,
y2=max(y),
color=background_color
)
But everytime I make the code run, the result display a different gradient scale, that is not smooth neither even straight right.
AND sometime the code is in error : TypeError: Length of y (100) must match number of rows in z (101)
I'm on it since too many time, turning around, and can't figure where I'm wrong...
I finally find something particularly cool, how to :
have both filled gradient curves in a different color (thanks to JohanC in this topic)
use x axis with datetime (thanks to Ffisegydd in this topic)
Here the code :
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
import matplotlib.dates as mdates
np.random.seed(2022)
st_date = '2022-11-01 00:00:00'
st_date = pd.to_datetime(st_date)
en_date = st_date + pd.DateOffset(days=7)
x = pd.date_range(start=st_date,end=en_date,freq='30min')
x = mdates.date2num(x)
y = np.random.normal(0.01, 1, len(x)).cumsum()
fig, ax = plt.subplots(figsize=(18, 5))
ax.plot(x, y, color='grey')
########################
# positives fill
#######################
grad1 = ax.imshow(
np.linspace(0, 1, 256).reshape(-1, 1),
cmap='Blues',
vmin=-0.5,
aspect='auto',
extent=[x.min(), x.max(), 0, y.max()],
# extent=[x[0], x[1], 0, y.max()],
origin='lower'
)
poly_pos = ax.fill_between(x, y.min(), y, alpha=0.1)
grad1.set_clip_path(
poly_pos.get_paths()[0],
transform=ax.transData
)
poly_pos.remove()
########################
# negatives fill
#######################
grad2 = ax.imshow(
np.linspace(0, 1, 256).reshape(-1, 1),
cmap='Reds',
vmin=-0.5,
aspect='auto',
extent=[x.min(), x.max(), y.min(), 0],
origin='upper'
)
poly_neg = ax.fill_between(x, y, y.max(), alpha=0.1)
grad2.set_clip_path(
poly_neg.get_paths()[0],
transform=ax.transData
)
poly_neg.remove()
########################
# decorations and formatting plot
########################
ax.xaxis_date()
date_format = mdates.DateFormatter('%d-%b %H:%M')
ax.xaxis.set_major_formatter(date_format)
fig.autofmt_xdate()
ax.grid(True)

Euler method python

I have some problems with plot. Exatlct solution here is true, but eulerbmethod gives the same curve, but much lower
import numpy as np
import matplotlib.pyplot as plt
# Define parameters
f = lambda x, y: 2*x
h = 0.1
x = np.arange(-10, 10, h)
x0 = 0
y0 = 2
# Explicit Euler Method
y = np.zeros(len(x))
y[x0] = y0
for i in range(0, len(x) - 1):
y[i + 1] = y[i] + h*f(x[i], y[i])
plt.figure(figsize=(12, 8))
plt.plot(x, y, 'b--', label='Euler')
plt.plot(x, 2+x**2, 'g', label='Exact')
plt.title('Numerical integration methods')
plt.xlabel('x')
plt.ylabel('y')
plt.grid()
plt.legend()
plt.show()
That's because your "exact solution" is not correct.
When you integrate, you have to consider that you have a non-zero value for x:

Adding contour labels doesn't label each contour, and removes some of the contour lines [duplicate]

The sample data is generated as follows,
import matplotlib as mpl
print(mpl.__version__) # 3.3.3
import matplotlib.pyplot as plt
import numpy as np
def f(x, y=0):
return np.piecewise(x, [x < 1, np.logical_and(1 <= x, x < 10), x >= 10], [lambda x: 0, lambda x: (x - 1) / 9 * 1000, lambda x: 1000])
x = np.logspace(-5, 5, 100)
y = np.logspace(-5, 5, 100)
X, Y = np.meshgrid(x, y)
Z = f(X, Y)
I try to plot using the following code, but some contours disappear after calling clabel.
fig, ax = plt.subplots(figsize=(5, 3), dpi=120)
cr = ax.contour(X, Y, Z, levels=3, colors='black')
ax.clabel(cr, inline=True, fontsize=8, fmt='%d')
ax.set_xscale('log')
ax.set_yscale('log')
plt.show()
This issue still appears even when contour linewidth and label font size are decreased.
fig, ax = plt.subplots(figsize=(5, 3), dpi=120)
cr = ax.contour(X, Y, Z, levels=3, colors='black', linewidths=0.6)
ax.clabel(cr, inline=True, fontsize=3, fmt='%d')
ax.set_xscale('log')
ax.set_yscale('log')
plt.show()
I cannot figure out how to fix the weird behaviours of contour and clabel, and I suspect it is due to their incompatibility with log scale.
It is indeed a problem of the log axes, especially around the asymptote zero. However, why not defining the log axes before plotting, so matplotlib can take this into consideration when plotting?
import matplotlib as mpl
print(mpl.__version__) # 3.3.3
import matplotlib.pyplot as plt
import numpy as np
def f(x, y=0):
return np.piecewise(x, [x < 1, np.logical_and(1 <= x, x < 10), x >= 10], [lambda x: 0, lambda x: (x - 1) / 9 * 1000, lambda x: 1000])
x = np.logspace(-5, 5, 100)
y = np.logspace(-5, 5, 100)
X, Y = np.meshgrid(x, y)
Z = f(X, Y)
fig, ax = plt.subplots(figsize=(5, 3), dpi=120)
ax.set_xscale('log')
ax.set_yscale('log')
cr = ax.contour(X, Y, Z, levels=3, colors='black')
ax.clabel(cr, inline=True, fontsize=8, fmt='%d')
plt.show()
Sample output:

Changing the linewidth and the color simultaneously in matplotlib

The figure above is a great artwork showing the wind speed, wind direction and temperature simultaneously. detailedly:
The X axes represent the date
The Y axes shows the wind direction(Southern, western, etc)
The variant widths of the line were stand for the wind speed through timeseries
The variant colors of the line were stand for the atmospheric temperature
This simple figure visualized 3 different attribute without redundancy.
So, I really want to reproduce similar plot in matplotlib.
My attempt now
## Reference 1 http://stackoverflow.com/questions/19390895/matplotlib-plot-with-variable-line-width
## Reference 2 http://stackoverflow.com/questions/17240694/python-how-to-plot-one-line-in-different-colors
def plot_colourline(x,y,c):
c = plt.cm.jet((c-np.min(c))/(np.max(c)-np.min(c)))
lwidths=1+x[:-1]
ax = plt.gca()
for i in np.arange(len(x)-1):
ax.plot([x[i],x[i+1]], [y[i],y[i+1]], c=c[i],linewidth = lwidths[i])# = lwidths[i])
return
x=np.linspace(0,4*math.pi,100)
y=np.cos(x)
lwidths=1+x[:-1]
fig = plt.figure(1, figsize=(5,5))
ax = fig.add_subplot(111)
plot_colourline(x,y,prop)
ax.set_xlim(0,4*math.pi)
ax.set_ylim(-1.1,1.1)
Does someone has a more interested way to achieve this? Any advice would be appreciate!
Using as inspiration another question.
One option would be to use fill_between. But perhaps not in the way it was intended. Instead of using it to create your line, use it to mask everything that is not the line. Under it you can have a pcolormesh or contourf (for example) to map color any way you want.
Look, for instance, at this example:
import matplotlib.pyplot as plt
import numpy as np
from scipy.interpolate import interp1d
def windline(x,y,deviation,color):
y1 = y-deviation/2
y2 = y+deviation/2
tol = (y2.max()-y1.min())*0.05
X, Y = np.meshgrid(np.linspace(x.min(), x.max(), 100), np.linspace(y1.min()-tol, y2.max()+tol, 100))
Z = X.copy()
for i in range(Z.shape[0]):
Z[i,:] = c
#plt.pcolormesh(X, Y, Z)
plt.contourf(X, Y, Z, cmap='seismic')
plt.fill_between(x, y2, y2=np.ones(x.shape)*(y2.max()+tol), color='w')
plt.fill_between(x, np.ones(x.shape) * (y1.min() - tol), y2=y1, color='w')
plt.xlim(x.min(), x.max())
plt.ylim(y1.min()-tol, y2.max()+tol)
plt.show()
x = np.arange(100)
yo = np.random.randint(20, 60, 21)
y = interp1d(np.arange(0, 101, 5), yo, kind='cubic')(x)
dv = np.random.randint(2, 10, 21)
d = interp1d(np.arange(0, 101, 5), dv, kind='cubic')(x)
co = np.random.randint(20, 60, 21)
c = interp1d(np.arange(0, 101, 5), co, kind='cubic')(x)
windline(x, y, d, c)
, which results in this:
The function windline accepts as arguments numpy arrays with x, y , a deviation (like a thickness value per x value), and color array for color mapping. I think it can be greatly improved by messing around with other details but the principle, although not perfect, should be solid.
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.collections import LineCollection
x = np.linspace(0,4*np.pi,10000) # x data
y = np.cos(x) # y data
r = np.piecewise(x, [x < 2*np.pi, x >= 2*np.pi], [lambda x: 1-x/(2*np.pi), 0]) # red
g = np.piecewise(x, [x < 2*np.pi, x >= 2*np.pi], [lambda x: x/(2*np.pi), lambda x: -x/(2*np.pi)+2]) # green
b = np.piecewise(x, [x < 2*np.pi, x >= 2*np.pi], [0, lambda x: x/(2*np.pi)-1]) # blue
a = np.ones(10000) # alpha
w = x # width
fig, ax = plt.subplots(2)
ax[0].plot(x, r, color='r')
ax[0].plot(x, g, color='g')
ax[0].plot(x, b, color='b')
# mysterious parts
points = np.array([x, y]).T.reshape(-1, 1, 2)
segments = np.concatenate([points[:-1], points[1:]], axis=1)
# mysterious parts
rgba = list(zip(r,g,b,a))
lc = LineCollection(segments, linewidths=w, colors=rgba)
ax[1].add_collection(lc)
ax[1].set_xlim(0,4*np.pi)
ax[1].set_ylim(-1.1,1.1)
fig.show()
I notice this is what I suffered.

Plotting a grid with Matplotlib

I want to plot a self-specified grid using Matplotlib in Python.
I know of the np.meshgrid function and can use it to obtain the array of different points I want to connect, but am unsure of how to then plot the grid.
Code example:
x = np.linspace(0,100,100)
y = np.linspace(0,10,20)
xv, yv = np.meshgrid(x, y)
Now, how can I plot a grid of this xv array?
You can turn a grid on/off with grid(), but it's only possible to have the grid lines on axis ticks, so if you want it hand-made, what about this:
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.patches import Rectangle
xs = np.linspace(0, 100, 51)
ys = np.linspace(0, 10, 21)
ax = plt.gca()
# grid "shades" (boxes)
w, h = xs[1] - xs[0], ys[1] - ys[0]
for i, x in enumerate(xs[:-1]):
for j, y in enumerate(ys[:-1]):
if i % 2 == j % 2: # racing flag style
ax.add_patch(Rectangle((x, y), w, h, fill=True, color='#008610', alpha=.1))
# grid lines
for x in xs:
plt.plot([x, x], [ys[0], ys[-1]], color='black', alpha=.33, linestyle=':')
for y in ys:
plt.plot([xs[0], xs[-1]], [y, y], color='black', alpha=.33, linestyle=':')
plt.show()
It's much faster by using LineCollection:
import pylab as pl
from matplotlib.collections import LineCollection
x = np.linspace(0,100,100)
y = np.linspace(0,10,20)
pl.figure(figsize=(12, 7))
hlines = np.column_stack(np.broadcast_arrays(x[0], y, x[-1], y))
vlines = np.column_stack(np.broadcast_arrays(x, y[0], x, y[-1]))
lines = np.concatenate([hlines, vlines]).reshape(-1, 2, 2)
line_collection = LineCollection(lines, color="red", linewidths=1)
ax = pl.gca()
ax.add_collection(line_collection)
ax.set_xlim(x[0], x[-1])
ax.set_ylim(y[0], y[-1])

Categories

Resources