Search code examples
pythonmatplotlibreinforcement-learningopenai-gymopenai-api

Matplotlib draw proportional triangle


My triangle drawing is appearing lopsided, how I make it proportional?

    points = np.array([[x, 10], [x/2, 10], [x+1/2, np.sqrt(5**2 - 2**2)]])
    pivot = plt.Polygon(points, closed = True)
   

Solution

  • If the slanted side is 5 long, and the triangle has height 2, half the width will be sqrt(5**2 + 2**2). Putting the left corner at position x,y, the right corner will be at the same y and the width added to x. The central point will be at x plus half the width and y+height:

    import matplotlib.pyplot as plt
    import numpy as np
    
    plt.style.use('dark_background')
    slanted_side = 5
    height = 2
    halfwidth = np.sqrt(slanted_side ** 2 - height ** 2)
    y = 10
    
    fig, axes = plt.subplots()
    # x = self.target_location
    x = 3
    pivot_left = (x, y)
    pivot_right = (x + 2 * halfwidth, y)
    pivot_top = (x + halfwidth, y + height)
    points = np.array([pivot_left, pivot_right, pivot_top])
    pivot = plt.Polygon(points, closed=True)
    axes.add_patch(pivot)
    axes.set_xlim(0, 20)
    axes.set_ylim(0, 20)
    axes.set_aspect('equal') # equal distances in x and y directions
    plt.show()
    

    example plot