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\n"
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
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\n"
uri = 'data:image/png;base64,' + urllib.quote(base64.b64encode(imgdata.buf))
print '<img src = "%s"/>' % uri
Complete python 3 version, putting together Paul's answer and metaperture's comment.
import matplotlib.pyplot as plt
import io
import urllib, base64
plt.plot(range(10))
fig = plt.gcf()
buf = io.BytesIO()
fig.savefig(buf, format='png')
buf.seek(0)
string = base64.b64encode(buf.read())
uri = 'data:image/png;base64,' + urllib.parse.quote(string)
html = '<img src = "%s"/>' % uri
Related
I got this code that has data stored in pickle format, I am trying to unpickle it. After it successfully ran, it was returning this output: <__main__.Container at 0x232ac6bde80>, but I want the data loaded into the DataFrame for further manipulations. I have searched StackOverflow for possible solutions to no avail. Kindly help. Here is the code:
import pandas as pd
import matplotlib.pyplot as plt
from matplotlib import rcParams
impor numpy as np
import tpickle
import skill_metrics as sm
from sys import version_info
def load_obj(name):
# Load object from file in pickle format
if version_info[0] == 2:
suffix = 'pkl'
else:
suffix = 'pkl3'
with open(name + '.' + suffix, 'rb') as f:
return pickle.load(f) # Python2 succeeds
class Container(object):
def __init__(self, pred1, pred2, pred3, ref):
self.pred1 = pred1
self.pred2 = pred2
self.pred3 = pred3
self.ref = ref
if __name__ == '__main__':
# Set the figure properties (optional)
rcParams["figure.figsize"] = [8.0, 6.4] #works
# rcParams['lines.linewidth'] = 2 # line width for plots
rcParams.update({'font.size': 12}) # font size of axes text
# Close any previously open graphics windows
plt.close("all")
# Read data from pickle file
load_obj('target_data')
df = pd.read_pickle('target_data.pkl')
df
Thanks.
import wordcloud
import numpy as np
from matplotlib import pyplot as plt
from IPython.display import display
import fileupload
import io
import sys
def _upload():
_upload_widget = fileupload.FileUploadWidget()
def _cb(change):
global file_contents
decoded = io.StringIO(change['owner'].data.decode('utf-8'))
filename = change['owner'].filename
print('Uploaded `{}` ({:.2f} kB)'.format(
filename, len(decoded.read()) / 2 **10))
file_contents = decoded.getvalue()
_upload_widget.observe(_cb, names='data')
display(_upload_widget)
_upload()
...
myimage = calculate_frequencies(file_contents)
plt.imshow(myimage, interpolation = 'nearest')
plt.axis('off')
plt.show()
This is the error I get on pycharm:
myimage = calculate_frequencies(file_contents)
NameError: name 'file_contents' is not defined
FileUploadWidget(label='Browse', _dom_classes=('widget_item', 'btn-group'))
I use the following code to plot my data. However, matplotlib does not plot the last data point.
First code gathers the data from the folder using loadtxt. After that I try to plot the data using:
plt.plot(datalistx, datalisty)
import matplotlib.pyplot as plt
import numpy as np
import os
MYDIR = os.path.dirname(os.path.realpath(__file__))
import numpy as np
NumS=20+1;
ydata=[]
folder_names = []
for entry_name in os.listdir(MYDIR):
entry_path = os.path.join(MYDIR, entry_name)
if os.path.isdir(entry_path):
folder_names.append(entry_name)
##print (entry_name)
ydata.append(round(float(entry_name), 3))
xdata=[]
folder_paths = []
for entry_name in os.listdir(MYDIR):
entry_path = os.path.join(MYDIR, entry_name)
if os.path.isdir(entry_path):
folder_paths.append(entry_path)
##print (entry_path)
##print (entry_path+'\Drifts')
path1=entry_path+"/"+"x."+"txt"
path2=entry_path+"/"+"y."+"txt"
datalistx = np.loadtxt(path1)
datalisty = np.loadtxt(path2)
plt.plot(datalistx,datalisty)
plt.xlim(0, 0.045)
plt.xlabel('Maximum Interstory Drift')
plt.ylabel('Sa(T1) (g)')
#plt.legend();
plt.savefig("20str",dpi=600)
plt.show()
Trying to return a simple plot (saved in StringIO) to web browser. After hours of reading, finally getting close, maybe.
import cgi
import cStringIO
import matplotlib.pyplot as plt
import numpy as np
def doit():
x = np.linspace(-2,2,100)
y = np.sin(x)
format = "png"
ggg = cStringIO.StringIO()
plt.plot(x, y)
plt.savefig(ggg, format=format)
data_uri = ggg.read().encode('base64').replace('\n', '')
img_tag = '<img src="data:image/png;base64,{0}" alt="thisistheplot"/>'.format(data_uri)
print("Content-type: text/html\n")
print("<title>Try Ageen</title>")
print("<h1>Hi</h1>")
print(img_tag)
doit()
It's returning a broken image icon. I've looked already read this: Dynamically serving a matplotlib image to the web using python, among others...
Actually, just figured it out. Will leave posted, as I haven't seen this approach being taken and hope it can help:
#!/usr/bin/env python
import cgi
import cStringIO
import matplotlib.pyplot as plt
import numpy as np
def doit():
x = np.linspace(-2,2,100)
y = np.sin(x)
format = "png"
sio = cStringIO.StringIO()
plt.plot(x, y)
plt.savefig(sio, format=format)
data_uri = sio.getvalue().encode('base64').replace('\n', '')
img_tag = '<img src="data:image/png;base64,{0}" alt="sucka" />'.format(data_uri)
print("Content-type: text/html\n")
print("<title>Try Ageen</title>")
print("<h1>Hi</h1>")
print(img_tag)
doit()
The goal is to have a client input a trigonometric function and have it returned on a subsequent page. Still any comments to help this code perform/look better are welcomed.
Problem : Need to transform a graphic image of matplotlib to a base64 image
Current Solution : Save the matplot image in a cache folder and read it with read() method and then convert to base64
New Problem : Annoyance : Need a workaround so I dont need to save the graphic as image in any folder. I want to just use the image in the memory. Doing unnecessary I/O is a bad practice.
def save_single_graphic_data(data, y_label="Loss", x_label="Epochs", save_as="data.png"):
total_epochs = len(data)
plt.figure()
plt.clf()
plt.plot(total_epochs, data)
ax = plt.gca()
ax.ticklabel_format(useOffset=False)
plt.ylabel(y_label)
plt.xlabel(x_label)
if save_as is not None:
plt.savefig(save_as)
plt.savefig("cache/cached1.png")
cached_img = open("cache/cached1.png")
cached_img_b64 = base64.b64encode(cached_img.read())
os.remove("cache/cached1.png")
return cached_img_b64
import cStringIO
my_stringIObytes = cStringIO.StringIO()
plt.savefig(my_stringIObytes, format='jpg')
my_stringIObytes.seek(0)
my_base64_jpgData = base64.b64encode(my_stringIObytes.read())
[edit] in python3 it should be
import io
my_stringIObytes = io.BytesIO()
plt.savefig(my_stringIObytes, format='jpg')
my_stringIObytes.seek(0)
my_base64_jpgData = base64.b64encode(my_stringIObytes.read()).decode()
I think at least ... based on the documentation http://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.savefig
For python 3
import base64
import io
pic_IObytes = io.BytesIO()
plt.savefig(pic_IObytes, format='png')
pic_IObytes.seek(0)
pic_hash = base64.b64encode(pic_IObytes.read())
The reason is both cStringIO and cStringIO.StringIO() are deprecated
I could not get answers above work, but this did:
import io
import base64
s = io.BytesIO()
plt.plot(list(range(100)))
plt.savefig(s, format='png', bbox_inches="tight")
plt.close()
s = base64.b64encode(s.getvalue()).decode("utf-8").replace("\n", "")
return '<img align="left" src="data:image/png;base64,%s">' % s