Make transparent color bar with height 0 in matplotlib

Leolime :

I have a 3d bar chart showing the network bandwidth of two 3 regions. I want to make the bars with 0 height transparent in matplotlib. In my output they are getting colors forming a square with height 0.

How can i do that?

Code:

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

data = np.array([
[1000,200],
[100,1000],
])

column_names = ['','Oregon','', 'Ohio','']
row_names = ['','Oregon','', 'Ohio']

fig = plt.figure()
ax = Axes3D(fig)

lx= len(data[0])            # Work out matrix dimensions
ly= len(data[:,0])

xpos = np.arange(0,lx,1)    # Set up a mesh of positions
ypos = np.arange(0,ly,1)
xpos, ypos = np.meshgrid(xpos+0.25, ypos+0.25)

xpos = xpos.flatten()   # Convert positions to 1D array
ypos = ypos.flatten()
zpos = np.zeros(lx*ly)

dx = 0.5 * np.ones_like(zpos)
dy = dx.copy()
dz = data.flatten()

cs = ['r', 'g'] * ly

ax.bar3d(xpos,ypos,zpos, dx, dy, dz, color=cs)

ax.w_xaxis.set_ticklabels(column_names)
ax.w_yaxis.set_ticklabels(row_names)
ax.set_zlabel('Mb/s')

plt.show()
gehbiszumeis :

There is an alpha parameter you can set for transparency which is a bit hidden in the documentation of bar3d since it is contained in the **kwargs available from mpl_toolkits.mplot3d.art3d.Poly3DCollection.

However there is not yet a possibility to give an array of alpha values for each individual bar as e.g. for the color key. Hence, you have to plot the transparent and not transparent ones separately with help of a mask for example.

# needs to be an array for indexing
cs = np.array(['r', 'g', 'b'] * ly)

# Create mask: Find values of dz with value 0
mask = dz == 0

# Plot bars with dz == 0 with alpha
ax.bar3d(xpos[mask], ypos[mask], zpos[mask], dx[mask], dy[mask], dz[mask],
         color=cs[mask], alpha=0.2)
# Plot other bars without alpha
ax.bar3d(xpos[~mask], ypos[~mask], zpos[~mask], dx[~mask], dy[~mask], dz[~mask],
         color=cs[~mask])

This gives

enter image description here

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=12094&siteId=1