Matplotlib:使用颜色图显示进程在其平均值附近的浓度

2024-09-30 16:32:35 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个pandas数据帧,包含100个给定过程的实现,在10个不同的日期观察(所有实现都从日期0的同一点开始)。 这样的数据帧可以通过以下方式生成:

import pandas as pd
import numpy as np
nbDates = 10
nbPaths = 100
rnd = np.random.normal(loc=0, scale=1, size=nbPaths*nbDates).reshape(nbDates,nbPaths)
sim = dict()
sim[0] = [100.0] * nbPaths
for t in range(nbDates):
    sim[t+1] = sim[t] + rnd[t]
sim = pd.DataFrame(sim)

现在我知道我可以像这样绘制数据帧中包含的100条路径

^{pr2}$

然后得到这样一个图:

enter image description here

但实际上我想做的是在每个日期绘制我的过程的最小值和最大值,并用一个彩色地图给两个极值点之间的区域涂上颜色,以反映曲线图中路径的集中程度(例如,在平均值周围为红色,当我们走到极端时逐渐变冷)。在

我已经研究过使用颜色贴图来实现这一点,但我还没有做到。如果有人知道一个直截了当的方法,那将是非常有帮助的。在

谢谢你!在


Tags: 数据import路径pandas颜色过程asnp
1条回答
网友
1楼 · 发布于 2024-09-30 16:32:35

你可以先用contourf绘制你的“注意力”等值线图,然后画出你的最大和最小值的线图,最后使用fill_between方法来掩盖轮廓图中不需要的部分。然而,正确的方法是在等高线图中屏蔽数组,但是我现在没有时间去弄清楚(看看numpy mask array options并尝试一下)。您需要遮罩数组,使其仅显示在最大值和最小值之间。在

{s>使用数组^代替^的示例:

import matplotlib.pyplot as plt
import pandas as pd
import numpy as np

## Your simulation code here ##

# Extract max, min, and mean values for each x coordinate
minimums = np.array(sim.min())
maximums = np.array(sim.max())
means = np.array(sim.mean())

x = np.array(sim.min().index)
y = np.arange(90,111)
X, Y = np.meshgrid(x, y)

# Insert your calculation for "concentration" in the line below
Z = (maximums[X] - minimums[X]) * Y // 100

# set up axes with matplotlib
fig, ax = plt.subplots()

# Plot contour, you'll want to change the levels
# depending on the range of values in your "concentration"
ax.contourf(X, Y, Z, levels=np.arange(0,20,.1), cmap=plt.get_cmap('jet'))

# Plot min, max, and mean
ax.plot(x, minimums, c='k')
ax.plot(x, maximums, c='k')
ax.plot(x, means, c='k', lw=2)

# Fill space outside min and max with white
ax.fill_between(x, maximums, 110, color='w')
ax.fill_between(x, 90, minimums, color='w')

这将产生以下输出:

Colormap fill between

您可以选择自己的函数来计算“浓度”以获得所需的填充图案。上面代码中的一个是为了说明如何让它依赖于绘图中的X和Y位置。祝你好运!在

相关问题 更多 >