Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
192 views
in Technique[技术] by (71.8m points)

python - matplotlib - store image in variable

I would like to store the image generated by matplotlib in a variable raw_data to use it as inline image.

import os
import sys
os.environ['MPLCONFIGDIR'] = '/tmp/'
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt

print "Content-type: image/png
"
plt.plot(range(10, 20))

raw_data = plt.show()

if raw_data:
    uri = 'data:image/png;base64,' + urllib.quote(base64.b64encode(raw_data))
    print '<img src = "%s"/>' % uri
else:
    print "No data"

#plt.savefig(sys.stdout, format='png')

None of the functions suit my use case:

  • plt.savefig(sys.stdout, format='png') - Writes it to stdout. This does help.. as I have to embed the image in a html file.
  • plt.show() / plt.draw() does nothing when executed from command line
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Have you tried cStringIO or an equivalent?

import os
import sys
import matplotlib
import matplotlib.pyplot as plt
import StringIO
import urllib, base64

plt.plot(range(10, 20))
fig = plt.gcf()

imgdata = StringIO.StringIO()
fig.savefig(imgdata, format='png')
imgdata.seek(0)  # rewind the data

print "Content-type: image/png
"
uri = 'data:image/png;base64,' + urllib.quote(base64.b64encode(imgdata.buf))
print '<img src = "%s"/>' % uri

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...