Я пытаюсь преобразовать фигуру гистограммы в массив.
Я делаю это, используя код ниже:
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( ) )