I think the same question was asked/answered on stackoverflow
here. I'll give a slightly different answer.
You can define a context manager that temporarily reroutes the
plt.show()
function:
import matplotlib.pyplot as plt
class Show:
'''Simple context manager to temporarily reroute plt.show().
This context manager temporarily reroutes the plt.show() function to
plt.savefig() in order to save the figure to the file specified in the
constructor rather than displaying it on the screen.'''
def __init__(self, name):
self._name = name
self._orig = None
def _save(self):
plt.savefig(self._name)
if False:
self._orig()
def __enter__(self):
self._orig = plt.show
plt.show = lambda: self._save()
return self
def __exit__(self, type, value, traceback):
if self._orig is not None:
plt.show = self._orig
self._orig = None
Then you can do
with Show('figure.png'):
visu.show()
to write the image to a file rather than displaying it on screen.
In the long run it is better to file a change request with docplex to get a function that directly exports an image.
------------------------------
Daniel Junglas
------------------------------
Original Message:
Sent: Mon August 10, 2020 09:25 AM
From: Archive User
Subject: How to save a Gantt chart as .png from Python docplex.cp.utils_visu
Originally posted by: mcastello
Hi everyone,
I'm currently working on a scheduling project with docplex using the CP optimizer.
I'm using the cp.utils_visu functions to create and display a gantt chart, which works great, but I would like to automatically save thig gantt as a .png file, and I don't see any 'savefig' function in utils_visu.
Here is my code to create and display my gantt chart:
import docplex.cp.utils_visu as visuif msol and visu.is_visu_enabled(): visu.timeline('Solution per orders') for l in dict_sorted_orders_by_line.keys(): for order in dict_sorted_orders_by_line[l]: visu.sequence(name=str(order)) for s in SKILLS: wt = msol.get_var_solution(wtasks[(order, s)]) if wt.is_present() and (wt.get_end()-wt.get_start()>0): wtname = compact_name(s.worker , 4) visu.interval(wt,int(l), wtname) visu.show()
Do you have any idea how I could do it ?
Thanks for your help.
#DecisionOptimization