[英]Colouring intersection between curves
I want to colour the intersection between a cumulative probability function (CDF) and the step function. 我想为累积概率函数(CDF)和阶跃函数之间的交点着色。 Here is my code 这是我的代码
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import seaborn as sns
from scipy.stats import norm
np.random.seed(1024)
mu = 200
sigma = 25
n_bins = 50
bins = np.array([121.95403681, 124.56265713, 127.17127746, 129.77989779,
132.38851812, 134.99713844, 137.60575877, 140.2143791 ,
142.82299943, 145.43161975, 148.04024008, 150.64886041,
153.25748074, 155.86610106, 158.47472139, 161.08334172,
163.69196205, 166.30058237, 168.9092027 , 171.51782303,
174.12644336, 176.73506368, 179.34368401, 181.95230434,
184.56092467, 187.16954499, 189.77816532, 192.38678565,
194.99540598, 197.6040263 , 200.21264663, 202.82126696,
205.42988729, 208.03850761, 210.64712794, 213.25574827,
215.8643686 , 218.47298892, 221.08160925, 223.69022958,
226.29884991, 228.90747023, 231.51609056, 234.12471089,
236.73333122, 239.34195154, 241.95057187, 244.5591922 ,
247.16781253, 249.77643285, 252.38505318])
my_norm = norm(loc=mu, scale=sigma)
x = np.random.normal(mu, sigma, size=100)
fig, ax = plt.subplots(figsize=(8, 4))
# Add a line showing the expected distribution.
y = ((1 / (np.sqrt(2 * np.pi) * sigma)) * np.exp(-0.5 * (1 / sigma * (bins - mu))**2))
y = y.cumsum()
y /= y[-1]
step_x = [10, 20, 30, 40, 50]
step_y = [0.02, 0.1, 0.3, 0.7, 1]
ax.plot(step_x, step_y, drawstyle='steps-pre')
cdf_x = range(n_bins+1)
ax.plot(cdf_x, y, color='black', linewidth=2)
# tidy up the figure
ax.grid(False)
# ax.legend(loc='right')
ax.set_title('CDF plot')
ax.set_xlabel('returns')
ax.set_ylabel('probability density')
However, by adding 但是,通过添加
ax.fill_between(cdf_x, step_y, where=None, facecolor='pink', interpolate=True)
after 后
ax.plot(cdf_x, y, color='black', linewidth=2)
It returns 它返回
ValueError: operands could not be broadcast together with shapes (51,) (5,)
How can I fix it since the shape are different? 由于形状不同,如何解决?
When use fill_between
you need to provide two y-data
with same length. 当使用fill_between
您需要提供两个长度相同的y-data
。 Here I suggest you fill it step by step: 在这里,我建议您逐步填写:
for i,iy in enumerate(step_y[1:]):
ax.fill_between(cdf_x[10*i+10:10*i+21],y[10*i+10:10*i+21],iy,facecolor='pink')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.