Skip to main content
 首页 » 编程设计

python之Pandas 条形图到 numpy 数组

2025年01月19日11落叶无声

我正在尝试将条形图转换为 numpy 数组。 我正在使用以下代码这样做:

df = pd.DataFrame.from_dict(data)     
 
fig = plt.figure() 
fig.add_subplot(1, 1, 1) 
 
df.plot.bar() 
 
plt.savefig('curr_bar_chart.png') 
 
numpy_array = fig2data(fig) 
plt.close() 
im = data2img(numpy_array) 

在问题的最后,我还附上了 fig2data 和 data2img 的代码。

我的问题: 保存的图像 (curr_bar_chart.png) 显示正常,但是当使用 im.show() 查看最终图像时,我得到一个没有任何数据的图(即空的用轴绘制)。

这非常令人费解,因为此设置适用于我在其他地方使用的其他 matplotlib 图。

正如 promise 的那样,其余代码:

 def fig2data(fig): 
    """ 
    @brief Convert a Matplotlib figure to a 4D numpy array with RGBA channels and return it 
    @param fig a matplotlib figure 
    @return a numpy 3D array of RGBA values 
    """ 
    # draw the renderer 
    fig.canvas.draw() 
 
    # Get the RGBA buffer from the figure 
    w, h = fig.canvas.get_width_height() 
    buf = np.fromstring(fig.canvas.tostring_argb(), dtype=np.uint8) 
    buf.shape = (w, h, 4) 
 
    # canvas.tostring_argb give pixmap in ARGB mode. Roll the ALPHA channel to have it in RGBA mode 
    buf = np.roll(buf, 3, axis=2) 
    return buf 
 
def data2img ( data ): 
    """ 
    @brief Convert a Matplotlib figure to a PIL Image in RGBA format and return it 
    @param fig a matplotlib figure 
    @return a Python Imaging Library ( PIL ) image 
    """ 
    # put the figure pixmap into a numpy array 
    w, h, d = data.shape 
    return Image.frombytes( "RGBA", ( w ,h ), data.tostring( ) ) 

请您参考如下方法:

那是因为你的fig确实是空的。您可以通过 plt.show() 代替 plt.savefig('curr_bar_chart.png') 来查看:

df = pd.DataFrame.from_dict(data)     
 
fig = plt.figure() 
fig.add_subplot(1, 1, 1) 
 
df.plot.bar() 
 
plt.show() 

您最终会看到两个图形,第一个(空的)是您的 fig。要解决此问题,您可以将 fig 的轴传递给 pandas 条形图。然后你会得到一个单一的情节,这是你的fig:

df = pd.DataFrame.from_dict(data)     
 
fig = plt.figure() 
ax = fig.add_subplot(1, 1, 1) 
 
df.plot.bar(ax = ax) 
 
plt.savefig('curr_bar_chart.png') 
 
numpy_array = fig2data(fig) 
plt.close() 
im = data2img(numpy_array) 
im.show()