Search code examples
pythonplotsympy

How to plot with x in decreasing order?


Sometimes y increases when x decreases:

enter image description here

from sympy import symbols, plot

p = symbols('p', positive=True)
h = (3.731444 - p**0.1902631) / 0.841728e-4

p_low = 150
p_high = 1013.25

plot(h, (p, p_low, p_high), axis_center=(p_low,0))

It can be more convenient to have a curve growing towards the top-right corner, it is possible to do that with sympy plot function?

I tried using reversed range and reversed extent without success.


Solution

  • It can be achieved by swapping the order of the xlim:

    plot(h, (p, p_low, p_high), axis_center=(p_low,0), xlim=(max, min))


    Using the plot's backend parameter you can access also to the matplolib backend. It has the advantage that you can inject your matplotlib commands. A subclass of BaseBackend is required. See source code of MatplotlibBackend for details.

    Here an illustrative example:

    import sympy.plotting.plot as plot
    from sympy.plotting.plot import MatplotlibBackend
    from sympy import symbols
    
    
    class SwapXAxis(MatplotlibBackend):
    
        def show(self):
            # here matplolib code
    
            for ax in self.ax:
                # reverse scale on x-axis
                ax.invert_xaxis()
                # anchor the y-axis at the new origin
                ax.spines['right'].set_position('zero')
                # adjust labels and ticks
                ax.yaxis.set_ticks_position("right")
                ax.yaxis.set_label_position("right")
    
            # call parent method
            super().show()
    
    
    p = symbols('p', positive=True)
    h = (3.731444 - p**0.1902631) / 0.841728e-4
    
    p_low = 150
    p_high = 1013.25
    
    
    plot(h, (p, p_low, p_high), backend=SwapXAxis, axis_center=(p_low,0))