Saving Python SymPy characters at a specific resolution / pixel density

I am wondering if there is a way to change the pixel density / resolution of sympy plots. For example, consider a simple piece of code below:

import sympy as syp x = syp.Symbol('x') miles_to_km = x * 1.609344 miles_to_km.evalf() graph = syp.plot(miles_to_km, show=False) graph.save('./figures/miles_to_km.png') graph.show() 

enter image description here

Notes:

  • When I tried using graph.savefig , I got AttributeError: 'Plot' object has no attribute 'saveimage' , I came across the saveimage method in some network resource, and it looks like it was a general approach - I think the API has changed

  • graph.save('./figures/miles_to_km.png', dpi=300) creates an error like: TypeError: save() got an unexpected keyword argument 'dpi'

  • Using the dpi attribute in plot does not cause any error, but does not affect image quality: graph = syp.plot(miles_to_km, dpi=300, show=False)

I also tried using the matplotlib backend:

 plt.figure() graph = syp.plot(miles_to_km, show=False) #graph.save('./figures/miles_to_km.png') plt.savefig('./figures/miles_to_km.png') graph.show() 

where plt = matplotlib.pyplot . However, the canvas is empty. Also relevant information may be that I run it on an IPython laptop with %matplotlib inline .

  • I am using SymPy v. 0.7.6

the backend workaround shows a graph in an IPython notebook, but it also creates a white canvas (like png)

 graph = syp.plot(miles_to_km, show=False) backend = graph.backend(graph) backend.fig.savefig('ch01_2.png', dpi=300) backend.show() 

enter image description here

EDIT and solution:

Thanks to Cody Piersall, the answer to this question is now resolved. I upgraded to IPython 4.0 (Jupyter laptop) and built it as follows

 graph = syp.plot(miles_to_km, show=False) backend = graph.backend(graph) backend.process_series() backend.fig.savefig('miles_to_km.png', dpi=300) backend.show() 
+5
source share
1 answer

Assuming you are using the matplotlib backend, which is the default if matplotlib is installed, you just need to import matplotlib.pyplot and use pyplot.savefig .

This works because sympy uses matplotlib to complete its construction, and since matplotlib is low-key, it knows which schedule you are working with.

Here is your example, but using savefig to save to png.

 import sympy as syp x = syp.Symbol('x') miles_to_km = x * 1.609344 miles_to_km.evalf() graph = syp.plot(miles_to_km, show=False) # Does not work in IPython Notebook, but works in a script. import matplotlib.pyplot as plt plt.savefig('./figures/miles_to_km.png', dpi=300) 

If you are on an IPython laptop, the above will not work, but you can still save them with the specified resolution. You just have to be a little harder about this.

 # works in IPython Notebook backend = graph.backend(graph) ackend.fig.savefig('300.png', dpi=300) backend.fig.savefig('20.png', dpi=20) 
+1
source

All Articles