如何用键(x,y)绘制字典

how to plot dictionary with key(x,y)

我有以下代码,我试图为案例创建一个字典:对于每个小时,每只猫,pct_chg 是什么。然后我想将其绘制为 3d 条形图..

我已经生成了字典,但一直在生成 3d 图。我需要将字典放入数据框中吗?如果是这样,我该怎么做?

代码:

finalres = {}
res ={}

for k in range(0,4):
    for v in range(0,10):
        samp =df[(df.index.hour == k) & (df.index.minute == 0) &(df.d==v )]
        r = (samp.c.shift(-1)/samp.c-1).fillna(0)
        res[v]=np.median(r)
        #if res[v] not in finalres:
          #  finalres[k,v] =(res[v])
        finalres[k,v]= res[v]
finalres

结果;

{(0, 0): 0.0,
 (0, 1): 0.0025106996266620607,
 (0, 2): 3.369215478188359e-05,
 (0, 3): 0.002175369937562399,
 (0, 4): 0.004421086273326047,
 (0, 5): 0.0016870411502398763,
 (0, 6): 0.0035694526244400837,
 (0, 7): 0.008261353566849428,
 (0, 8): 0.0034017655163030014,
 (0, 9): -0.0008439103429652706,
 (1, 0): 0.0017808170388573519,
 (1, 1): 0.0,
 (1, 2): 0.026236201421442673,
 (1, 3): 0.007099681676741021,
 (1, 4): 0.005533565088169046,
 (1, 5): 0.0064369036590845585,
 (1, 6): 0.0,
 (1, 7): 0.0033877060148719274

您可以根据生成的字典创建 3D 条形图,而无需加载到数据框中。

以下代码片段是一种实现方式:

import numpy as np
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt

a = finalres # Store your dictionary here

x, y = zip(*a.keys()) 
z = list(a.values())

# Plotting
fig = plt.figure()
ax = fig.gca(projection = '3d')

dx = .25 * np.ones(len(x))
dy = .25 * np.ones(len(y))
dz = z

ax.set_xlabel('X')
ax.set_ylabel('Y')
ax.set_zlabel('Z')
ax.bar3d(x, y, z, dx, dy, dz, color = 'blue')

plt.show()

问题中使用的示例数据的图表如下所示: