Issue
I am facing an issue with drawing triangle borders using Matplotlib in Python. I want to create a specific pattern, but I'm encountering unexpected behavior. I need assistance in identifying and resolving the problem.
this is my code
import numpy as np
import matplotlib.pyplot as plt
N = 5
A = np.array([(x, y) for y in range(N, -1, -1) for x in range(N + 1)])
t = np.array([[1, 1], [-1, 1]])
A = np.dot(A, t)
# I have defined a triangle
fig = plt.figure(figsize=(10, 10))
triangle = fig.add_subplot(111)
X = A[:, 0].reshape(N + 1, N + 1)
Y = A[:, 1].reshape(N + 1, N + 1)
for i in range(1, N + 1):
for j in range(i):
line_x = np.array([X[i, j + 1], X[i, j], X[i - 1, j]])
line_y = np.array([Y[i, j + 1], Y[i, j], Y[i - 1, j]])
triangle.plot(line_y,line_x, color='black', linewidth=1)
plt.show()
but I am getting this image, as u can see,
At corner extra lines are coming, as i encircled it. I dont want this extra line, i tried to solved it using loop, eventhough one extra line will keep remain
for i in range(6):
if i == N-1 :
for j in range(i-1):
line_x = np.array([X[i , j+1], X[i, j],X[i-1, j]])
line_y = np.array([Y[i, j+1], Y[i, j], Y[i-1, j]])
triangle.plot(line_y, line_x, color='black', linewidth=1)
pass
else:
for j in range(i):
line_x = np.array([X[i , j+1], X[i, j],X[i-1, j]])
line_y = np.array([Y[i, j+1], Y[i, j], Y[i-1, j]])
triangle.plot(line_y,line_x, color='black', linewidth=1)
pass
plt.show() kindly resolve the issue
Solution
The lines you want to delete belong to the triangules generated in the first (i = 1, j = 0) and last (i = N, J = N - 1) iterations of the nested for
loops:
import numpy as np
import matplotlib.pyplot as plt
N = 5
A = np.array([(x, y) for y in range(N, -1, -1) for x in range(N + 1)])
t = np.array([[1, 1], [-1, 1]])
A = np.dot(A, t)
# I have defined a triangle
fig = plt.figure(figsize=(10, 10))
triangle = fig.add_subplot(111)
X = A[:, 1].reshape(N + 1, N + 1)
Y = A[:, 0].reshape(N + 1, N + 1)
for i in range(1, N + 1):
for j in range(i):
if i == 1: # Lower right triangle
line_x = np.array([X[i, j + 1], X[i, j]])
line_y = np.array([Y[i, j + 1], Y[i, j]])
elif j == N - 1: # Upper right triangle
line_x = np.array([X[i, j], X[i - 1, j]])
line_y = np.array([Y[i, j], Y[i - 1, j]])
else:
line_x = np.array([X[i, j + 1], X[i, j], X[i - 1, j]])
line_y = np.array([Y[i, j + 1], Y[i, j], Y[i - 1, j]])
triangle.plot(line_x, line_y, color='black', linewidth=1)
plt.show()
Answered By - FJSevilla
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.