diffracteD
diffracteD

Reputation: 758

plotting 3d barchart from a 3D list

I have a dataset looks like(contains ~25 data-points):

x=[2.225  2.325  2.425  2.075  2.375  1.925  1.975  1.775  1.975  2.375]  
y=[147.75  130.25  161.75  147.75  165.25  151.25  158.25  151.25  172.25  123.25]  
z=[-1.36, -0.401, -0.741, -0.623, -0.44, -0.37, 0.120, 2.8, 0.026, -1.19]  

I'm trying to plot a 3D-bar chart using the data.
I was trying like:

from mpl_toolkits.mplot3d import Axes3D         
fig_3d_bar = plt.figure(figsize=(7, 5))  
dx = fig_3d_bar.add_subplot(111, projection='3d')  

x_pos = np.array(x)  
y_pos = np.array(y)  
z_pos = np.zeros(len(x))    

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

dx.bar3d(x_pos, y_pos, z_pos, dx, dy, dz, color='#00ceaa')  

But this is giving me an error report as:

    dx.bar3d(x_pos, y_pos, z_pos, dx, dy, dz, color='#00ceaa')  
AttributeError: 'numpy.ndarray' object has no attribute 'bar3d'  

A little help would serve great. Don't know what is going wrong.
thank you.

Upvotes: 2

Views: 239

Answers (1)

spfrnd
spfrnd

Reputation: 936

There is an error in your code. You use the variable name dx for both the Axes object and the size of the bars. I guess you want

ax = fig_3d_bar.add_subplot(111, projection='3d')
ax.bar3d(x_pos, y_pos, z_pos, dx, dy, dz, color='#00ceaa')   

Bar Sizes

The bars appear very wide in the plot because of the different scales of the x- and y-data. You can adjust them by scaling dx and dy accordingly.

dx = np.ones(len(x))*0.1
dy = np.ones(len(y))*5

Bar Colors

The colors of the bars can be adapted to the z-values by using a ScalarMappable instance. For this you need a norm object that scales the z-values to the range [0,1]. You can choose any of the predefined colormaps or create your own.

import matplotlib.colors as cls
import matplotlib.cm as cm

norm = cls.Normalize() # Norm to map the z values to [0,1]
norm.autoscale(z)
cmap = cm.ScalarMappable(norm, 'jet') # Choose any colormap you want

ax.bar3d(x_pos, y_pos, z_pos, dx, dy, dz, color=cmap.to_rgba(z))

Upvotes: 1

Related Questions