plotly.graph_objects is saving old info - python

I have created a graph in python utilizing the follow sample code.
import plotly.graph_objects as go
from matplotlib.pyplot import figure
image_path = "C:/Users/Me/Pictures/x.png"
fig = go.Figure(go.Indicator(...))
fig.write_image(image_path)
When I go to create new image with this same code, the old data is still in there somewhere and saves with the old data rather than the new data.
I tried using fig.close() but I get an error 'Figure' object has no attribute 'close'. I also tried using plt.close('all') but no luck.
I tried looking on the ploty.graph_objects page but was not able to find how to close the image or save new image with new data.
I also tried clearing the figure data/layout after each run with fig.data = [] and fig.layout = {}
I also tried fig.show() which when looping through images, does show the correct image but the saved image still shows old data.
Any ideas on how to save a figure graph object from plotly with new data?

generating four indicators in a loop
save to a filename x.png and x_.png
x.png and x_750.png are the same so file is definitely being overwritten
import plotly.graph_objects as go
from pathlib import Path
p = Path.cwd().joinpath("indicator_images")
if not p.is_dir():
p.mkdir()
for v in [300,450,600,750]:
fig = go.Figure(go.Indicator(
mode = "gauge+number",
value = v,
title = {'text': "Speed"},
domain = {'x': [0, 1], 'y': [0, 1]}
))
fig.write_image(p.joinpath("x.png"))
fig.write_image(p.joinpath(f"x_{v}.png"))

Related

Is there a function to save an image as bytearray in pyqtgraph?

I am trying to create a function to export an animation to a video format. I believe the first step in this is to transform a single image into a bytearray, but I can't figure out how to do this.
I tried adjusting the following program which exports a single image:
import pyqtgraph as pg
import pyqtgraph.exporters
# generate something to export
plt = pg.plot([1, 5, 2, 4, 3])
# create an exporter instance, as an argument give it
# the item you wish to export
exporter = pg.exporters.ImageExporter(plt.plotItem)
# save to file
exporter.export('fileName.png')
from this website. But I couldn't get it to store it as a bytearray. Does anybody know how to do this, or how else to approach exporting an entire animation?

Save wfdb output as an image

I am trying to plot ECG signals using wfbd package
It is working but I can't save the output in an image file.
here is the code I am using:
record = wfdb.rdrecord('ptb/records100/00000/00001_lr')
wfdb.plot_wfdb(record=record, title='ECG', figsize=(20,20))
fig1=plt.figure()
fig1.savefig('test.png', dpi=100)
the image saved is always empty
anyone suggestions ?
What you want to do is save the figure object that wfdb plotted the signal to.
However, you're creating a new figure and saving it.
wfdb.plot_wfdb has a return_fig argument to get the figure object you want.
Call savefig on that object.
Doc here
fig = wfdb.plot_wfdb(..., return_fig=True)
fig.savefig("test.png")

Plotly in Python: show mean and variance of selected data

I am generating histograms using go.Histogram as described here. I am getting what is expected:
What I want to do is to show some statistics of the selected data, as shown in the next image (the white box I added manually in Paint):
I have tried this and within the function selection_fn I placed the add_annotation described here. However, it does nothing. No errors too.
How can I do this?
Edit: I am using this code taken from this link
import plotly.graph_objects as go
import numpy as np
x = np.random.randn(500)
fig = go.Figure(data=[go.Histogram(x=x)])
fig.show()
with obviously another data set.

Image not updating in python plot during animation

The Problem:
I'm trying to simulate a live video by cycling through a series of still images I have saved in a directory, but when I add the animation and update functions my plot is displayed empty.
Background on why I'm doing this:
I believe its important for me to do it this way rather than a complete change of approach, say turning the images into a video first then displaying that, because what I really want to test is the image analysis I will be adding and then overlaying on each frame. The final application will be receiving frames one by one from a camera and will need to do some processing, display the image + annotations + output the data as .csv etc... I'm simulating this for now because I do not have any of the hardware to generate the images and will not have it for several months during which time I need to get the image processing set up, but I do have access to some sets of stills that are approximately what will be produced. In case its relevant my simulation images are 1680x1220 and are 1.88 Mb TIFFs, though I could covert and compress them if needed, and in the final form the resolution will be a bit higher and probably the image format could be adjusted if needed.
What I have tried:
I followed an example to list all files in a folder, and an example
to update a plot. However, the plot displays blank when I run the
code.
I added a line to print the current file name, and I can see this
cycling as expected.
I also made sure the images will display in the plot if I just create
a plot and add one image, and they do. But, when combined with the
animation function the plot is blank and I'm not sure what I've done
wrong/failed to include.
I also tried adding a plt.pause() in the update, but again this
didn't work.
I increased the interval up to 2000 to give it more time, but that didn't work. I believe 2000 is extreme, I'm expecting it should work with more like 20-30fps. Going to 0.5fps tells me the code is wrong or incomplete, rather than it just being a question of needing time to read the image file.
I appreciate no one else has my images, but they are nothing special. I'm using 60 images but I guess it could be tested with any 2 random images and setting range(60) to range(2) instead?
The example I copied originally demonstrated the animation function by making a random array, and if I do that it will show a plot that updates with random squares as expected.
Replacing:
A = np.random.randn(10,10)
im.set_array(A)
...with my image instead...
im = cv2.imread(files[i],0)
...and the plot remains empty/blank. I get a window shown called "Figure1" (like when using the random array), but unlike with the array there is nothing in this window.
Full code:
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
import os
import cv2
def update(i):
im = cv2.imread(files[i],0)
print(files[i])
#plt.pause(0.1)
return im
path = 'C:\\Test Images\\'
files = []
# r=root, d=directories, f = files
for r, d, f in os.walk(path):
for file in f:
if '.TIFF' in file:
files.append(os.path.join(r, file))
ani = FuncAnimation(plt.gcf(), update, frames=range(60), interval=50, blit=False)
plt.show()
I'm a python and a programming novice so have relied on adjusting examples others have given online but I have only a simplistic understanding of how they are working and end up with a lot of trial and error on the syntax. I just can't figure out anything to make this one work though.
Cheers for any help!
The main reason nothing is showing up is because you never add the images to the plot. I've provided some code below to do what you want, be sure to look up anything you are curious about or don't understand!
import glob
import os
from matplotlib import animation
import matplotlib.image as mpimg
import matplotlib.pyplot as plt
IMG_DIRPATH = 'C:\\Test Images\\' # the folder with your images (be careful about
# putting spaces in directory names!)
IMG_EXT = '.TIFF' # the file extension of your images
# Create a figure, and set to the desired size.
fig = plt.figure(figsize=[5, 5])
# Create axes for the current figure so that images can be sized appropriately.
# Passing in [0, 0, 1, 1] makes the axes fill the whole figure.
# frame_on=False means we won't have a bounding box, and setting xticks=[] and
# yticks=[] means that we won't have pesky tick marks along our image.
ax_props = {'frame_on': False, 'xticks': [], 'yticks': []}
ax = plt.axes([0, 0, 1, 1], **ax_props)
# Get all image filenames.
img_filepaths = glob.glob(os.path.join(IMG_DIRPATH, '*' + IMG_EXT))
def update_image(img_filepath):
# Remove all existing images on the axes, and restore our settings.
ax.clear()
ax.update(ax_props)
# Read the current image.
img = mpimg.imread(img_filepath)
# Add the current image to the plot axes.
ax.imshow(img)
anim = animation.FuncAnimation(fig, update_image, frames=img_filepaths, interval=250)
plt.show()

Writing pandas/matplotlib image directly into XLSX file

I am generating plots in pandas/matplotlib and wish to write them to an XLSX file. I am not looking to create native Excel charts; I am merely writing the plots as non-interactive images. I am using the XlsxWriter library/engine.
The closest solution I have found is the answer to this SO question, which suggests using the XlsxWriter.write_image() method. However, this method appears to take a filename as its input. I am trying to programmatically pass the direct output from a pandas/matplotlib plot() call, e.g. something like this:
h = results.resid.hist()
worksheet.insert_image(row, 0, h) # doesn't work
or this:
s = df.plot(kind="scatter", x="some_x_variable", y="resid")
worksheet.insert_image(row, 0, s) # doesn't work
Is there any way to accomplish this, short of the workaround of writing the image to a disk file first?
Update
Answer below got me on the right track and am accepting. I needed to make a few changes, mainly (I think) because I am using Python 3 and perhaps some API changes. Here is the solution:
from io import BytesIO
import matplotlib.pyplot as plt
imgdata = BytesIO()
fig, ax = plt.subplots()
results.resid.hist(ax=ax)
fig.savefig(imgdata, format="png")
imgdata.seek(0)
worksheet.insert_image(
row, 0, "",
{'image_data': imgdata}
)
The "" in the insert_image() code is to trick Excel, which is still expecting a filename/URL/etc.
You can save the image to memory as a file object (not to disk) and then use that when inserting to Excel file:
import matplotlib.pyplot as plt
from cStringIO import StringIO
imgdata = StringIO()
fig, ax = plt.subplots()
# Make your plot here referencing ax created before
results.resid.hist(ax=ax)
fig.savefig(imgdata)
worksheet.insert_image(row, 0, imgdata)

Categories

Resources