how to plot dictionary with key(x,y)

Viewed 286

Im having the following code where im trying to create a dictionary for the case: for every hour, and every cat, what is the pct_chg. Then i want to plot it as a 3d bar chart..

I have generated the dictionary, but stuck on generating the 3d plot.. do i need to put the dictionary into a dataframe . if so, how do i do that ?

the code:

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

the results;

{(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
1 Answers

You can create a 3D Bar plot from the dictionary you have generated, without loading into a dataframe.

The following code snippet is one way of doing that:

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()

The plot from the sample data used in the question will look like this: enter image description here

Related