I’m looking to create a program that will randomly generate lines (that are inequalities) and that will show the area that satisfies the constraints.
I don’t mind which libraries are used so feel free to use sympy, numpy etc
I will show my current code but this just fills the area between 2 lines and doesn’t use inequalities at all.
If possible a legend would be nice but I can always add one myself.
JavaScript
x
17
17
1
import matplotlib.pyplot as plt
2
import numpy as np
3
4
x = np.arange(0,100,0.1)
5
y1 = 2*x
6
y2 = 0.5*x+5
7
plt.ylim(0, 20)
8
plt.xlim(0, 20)
9
10
# Plotting of lines
11
plt.plot(x, y1,
12
x, y2)
13
14
# Filling between line y3 and line y4
15
plt.fill_between(x, y1, y2, color='grey', alpha=0.5)
16
plt.show()
17
Advertisement
Answer
You can combine multiple sympy plots via show=False
and appending plots. This can be used to add lines:
JavaScript
1
10
10
1
from sympy import symbols, Eq, plot_implicit
2
3
x, y = symbols('x y')
4
p1 = plot_implicit(And(x > 3, y > x), show=False)
5
p2 = plot_implicit(Eq(x, 3), line_color='crimson', show=False)
6
p3 = plot_implicit(Eq(x, y), line_color='crimson', show=False)
7
p1.append(p2[0])
8
p1.append(p3[0])
9
p1.show()
10
Alternatively, you could make use of the markers=
parameter to add lines or points. annotations=
can be used to add text.
JavaScript
1
11
11
1
from sympy import symbols, Eq, plot_implicit
2
3
x, y = symbols('x y')
4
plot_implicit(And(x > 3, y > x),
5
markers=[{'args': [[3, 3], [-5, 5]], 'color': 'r', 'ls': '--'},
6
{'args': [[-5, 5], [-5, 5]], 'color': 'r', 'ls': '--'}],
7
annotations=[{'xy': (3, 2), 'text': " $x = 3$",
8
'ha': 'left', 'va': 'center', 'color': 'r'},
9
{'xy': (2, 2), 'text': "$x = y$",
10
'ha': 'right', 'va': 'center', 'color': 'r', 'rotation': 45}])
11