如何使用matplotlib将颜色渐变附加到每个条形图

时间:2017-10-13 16:41:56

标签: matplotlib

我在matplotlib中创建条形图的标准方法是使用ax.bar3d。这具有返回纯色块的缺点。有谁知道如何将渐变颜色附加到每个条形图?我想从https://arxiv.org/pdf/1706.09289.pdf再现图1。

1 个答案:

答案 0 :(得分:0)

试试这个:

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

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

x_data, y_data = np.meshgrid(np.arange(5),np.arange(3))
z_data = np.random.rand(3,5)
colors = ['r','g','b'] # colors for every line of y

# plot colored 3d bars
for i in xrange(3):  # cycle though y 
    # I multiply one color by len of x (it is 5) to set one color for y line
    ax.bar3d(x_data[i], y_data[i], z_data[i], 1, 1, z_data[i], alpha=0.1, color=colors[i]*5)
    # or use random colors
    # ax.bar3d(x_data[i], y_data[i], z_data[i], 1, 1, z_data[i], alpha=0.1, color=[np.random.rand(3,1),]*5)
plt.show()

结果: enter image description here