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

241 views Asked by At

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.

2

There are 2 answers

0
JohanC On BEST ANSWER

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

0
Natsfan On

Yes, there is. Add matplotlib to your python distribution and then import it in your code. I usually use the following when importing it. import matplotlib.pyplot as plt. Then I can use the following line also in my python code: plt.plot(x, y)` This will give you a simple x,y plot of the values you have defined.

In the line import matplotlib.pyplot as plt, I'm loading maplotlib as plt. This allows you to refer to it as plt. The x-axis can be defined by the user as a set of values or you can generate the x-values by using something like x = np.linspace(0, 20, 200) where linspace is a function to generate equally spaced points. The 0 and 20 refer to the xmin and xmax values while 200 is the number of x-values generated.

you can also simply do

x = (1,3,5,9,11,13)
y = (1,9,25,81,121,169)

and plt.plot(x,y)