# How to plot a 3-axis bar chart with matplotlib (and pandas + jupyter)

I'm a bit confused about how to go about plotting a 3-axis bar chart:

So my jupyter notebook reads in an excel/sheet and I have a table:

     2001  2002   2003   2004
Mar  15    16     14     18
Jun  23    25     28     24
Jul  24    23     22     26


I'm a bit confused about how to go about building the visualization and having the axes/labels set up correctly.

• May 16, 2018 at 12:31
• @manoharamrutkar I have seen those, but I'm sorry my confusion lies in how to translate the table to the appropriate axes for plotting. May 16, 2018 at 12:48

I am sure you have found your answer by now, but for others.

Setup

from mpl_toolkits.mplot3d import axes3d
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from matplotlib import style

data_dic = {2001 : [15, 23, 24],
2002 : [16, 25, 23],
2003 : [14, 18, 22],
2004 : [18, 24, 26]}

df = pd.DataFrame(data_dic, index=["Mar",
"Jun",
"Jul"])



Data

         2001  2002   2003   2004
Mar  15    16     14     18
Jun  23    25     28     24
Jul  24    23     22     26


Data Wrangling

xlabels = df.columns
ylabels = df.index
x = np.arange(xlabels.shape[0])
y = np.arange(ylabels.shape[0])
z = np.vstack([df[2001].values, df[2002].values, df[2003].values, df[2004].values]).ravel()


Plotting 3-axis bar chart

# Set plotting style
plt.style.use('fivethirtyeight')

x_M, y_M = np.meshgrid(x, y, copy=False)

fig = plt.figure(figsize=(10, 10))
ax = fig.add_subplot(111, projection='3d')

# Making the intervals in the axes match with their respective entries
ax.w_xaxis.set_ticks(x + 0.5/2.)
ax.w_yaxis.set_ticks(y + 0.5/2.)

# Renaming the ticks as they were before
ax.w_xaxis.set_ticklabels(xlabels)
ax.w_yaxis.set_ticklabels(ylabels)

# Labeling the 3 dimensions
ax.set_xlabel('Year')
ax.set_ylabel('Month')
ax.set_zlabel('Sales')

# Choosing the range of values to be extended in the set colormap
values = np.linspace(0.2, 1., x_M.ravel().shape[0])

# Selecting an appropriate colormap
colors = plt.cm.Spectral(values)
ax.bar3d(x_M.ravel(), y_M.ravel(), z*0, dx=0.5, dy=0.5, dz=z, color=colors)
plt.show()