Search code examples
matplotlibplotjupyterinequalityinequalities

Using matplotlib, is there a way to create simple 2d plots of basic inequalities


enter image description here

How can one creat a simple, 2 dimensional plot of a basic inequality. The result is a numbered line with one or two lines overlaid. The line or lines would begin or end with an arrow, a filled-in circle, or an open circle.


Solution

  • Some techniques that you can use:

    • create a plot, setting the x-axis in the center, hide all the other spines
    • use line plots to create the lines and the arrows
    • set the xticks 'inout' and make the ticks longer
    • use filled markers for the special point; the fill color can be either white or turquoise given a hollow versus filled effect
    • set the zorders so that the lines are on top of the xaxis
    • if you want multiple of these axes, use plt.subplots(nrows=...), setting the figsize accordingly

    Here is some code to get you started.

    import matplotlib.pyplot as plt
    
    fig, ax = plt.subplots(nrows=1)
    x0 = -5
    x1 = 5
    p = 3
    ax.set_ylim(-1, 1)
    ax.set_xlim(x0 - 0.4, x1 + 0.4)
    ax.set_xticks(range(x0, x1 + 1))
    ax.set_yticks([])
    ax.tick_params(axis='x', direction='inout', length=10)
    ax.spines['bottom'].set_position('zero')
    ax.spines['bottom'].set_zorder(0)
    for dir in ['left', 'right', 'top']:
        ax.spines[dir].set_visible(False)
    ax.plot([x0 - 0.4, p], [0, 0], color='turquoise', lw=1)
    ax.plot([x0 - 0.2, x0 - 0.4, x0 - 0.2], [0.2, 0, -0.2], color='turquoise', lw=1)
    ax.plot([x1 + 0.2, x1 + 0.4, x1 + 0.2], [0.2, 0, -0.2], color='black', lw=1)
    ax.plot(p, 0, linestyle='', marker='o', fillstyle='full', markerfacecolor='white', markeredgecolor='turquoise',
            markersize=5, lw=2, zorder=3)
    ax.set_aspect('equal')
    plt.show()
    

    example plot