I have the following problem:
I have a Python script that has a class called "Triangle" which has a method called "plot ()", it returns the graph of a triangle. In this same script I have another class called "Circle" that has a method called "plot ()", this returns the graph of the circle. With the above I want to create a method in the class "Triangle" that I graph the triangle and circle in a single graph from their respective methods --- observe the method (plotintrianglecircle) . How can I achieve the above?
I am using matplotlib. I've tried for a long time but I still can not.
I have done the following in code:
This is the "Circle" class:
class Circle():
def __init__(self, center, radius):
self.center = center
self.radius = radius
def plot(self):
from matplotlib import pyplot as plt
import numpy as np
alpha = np.linspace(0, 2 * np.pi, 1000)
self.x = self.center[0] + self.radius * np.cos(alpha)
self.y = self.center[1] + self.radius * np.sin(alpha)
fig = plt.figure()
ax = fig.add_subplot(111)
# plot circle
ax.plot(self.x, self.y, 'r-', label='Circle')
ax.axis('equal')
ax.grid(ls='--', lw=0.6)
ax.legend()
return ax
For the Triangle class I have the following code:
class Triangle():
def __init__(self, vertices):
import numpy as np
# (3, 2) Array of triangle vertices
self.v = np.array(vertices)
def plot(self):
import numpy as np
from matplotlib import pyplot as plt
fig = plt.figure()
ax = fig.add_subplot(111)
# plot triangle
ax.plot(np.hstack((self.v[:, 0], self.v[0, 0])),
np.hstack((self.v[:, 1], self.v[0, 1])),
'k-', label='Triangle')
ax.axis('equal')
ax.grid(ls='--', lw=0.6)
ax.legend()
return ax
def intrianglecircle(self, radius=None):
import numpy as np
if radius is None:
self.radius = 0.05 * self.inradius()
else:
self.radius = radius
# random number [0, 1]
r1, r2 = np.random.random(), np.random.random()
# x-coordinate
px = (1-np.sqrt(r1))*self.v[0][0]+(np.sqrt(r1)*(1-r2)) * \
self.v[1][0]+(np.sqrt(r1)*r2)*self.v[2][0]
# y-coordinate
py = (1-np.sqrt(r1))*self.v[0][1]+(np.sqrt(r1)*(1-r2)) * \
self.v[1][1]+(np.sqrt(r1)*r2)*self.v[2][1]
# center circle
self.center = np.array([px, py])
return Circle(self.center, self.radius)
def plotintrianglecircle(self):
import numpy as np
c = Circle(self.center, self.radius)
fig2 = c.plot()
fig2.plot(np.hstack((self.v[:, 0], self.v[0, 0])),
np.hstack((self.v[:, 1], self.v[0, 1])),
'k-', label='Triangle')
fig2.legend()
return
Observe the plotintrianglecircle method of the Triangle class. What I want to do is just reuse the plot method of the Triangle class . strong> to avoid writing the lines where fig2.plot (....) . How can I do it?
You can execute the code with these data so that you can see the result:
vertices = [[2, 1.5], [4.5, 4], [6, 2]]
t = Triangle(vertices)
t.intrianglecircle(1)
t.plotintrianglecircle()
I just want to reuse the plot method of the Triangle class as I mentioned earlier.