Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sympy.plotting.plot strange xlabel position

Tags:

python

plot

sympy

When setting 'xlabel' to a string value in a plot statement in sympy, the label is placed at the far right of the graph. If the label is not set in the program, and i click on the checkmark and set the label there, it's positioned in the middle of the X axis.

here's an example:

from sympy import sin
from sympy import symbols
from sympy.plotting import plot

x = symbols('x')
y = sin(x)

p1=plot(y,(x,0,7),xlabel="x data")
p2=plot(y,(x,0,7))

figure 1 has the X-axis label to the far right. if you open figure 2, and click the checkmark at the top to set the label interactively, it places it correctly in the middle of the axis.

any way to instruct the program to centre the label?

like image 943
Milothicus Avatar asked Oct 20 '22 18:10

Milothicus


1 Answers

Sympy's implementation of matplotlib for plotting is convenient, but rather limited compared to the full matplotlib functionality. If you want to change the label location on the axis you need to access the backend ax object from your plot. Here's how to do that:

fig = p1._backend.fig
ax = p1._backend.ax

ax.xaxis.set_label_coords(0.5,0)

fig.savefig('test.png')

image showing axis label centered below graph

This will save your graph as test.png (see picture). If you are using a gui like jupyter you can also show the plot by calling fig, but in command line interfaces this will not work. I do not know any convenient way to show the plot (like p1.show() would) using only the sympy interface (so without importing matplotlib.pyplot). If you know how to use matplotlib however you can manipulate both the figure and axis objects in far more detail.

like image 57
Dominique Fuchs Avatar answered Nov 04 '22 00:11

Dominique Fuchs