我正在尝试将条形图转换为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图。
正如所承诺的,其余的代码:
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( ) )
答案 0 :(得分:1)
那是因为你的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 bar plot。然后,您将得到一个单独的图,即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()