loliki
loliki

Reputation: 957

Matplotlib draw triangle with given sides from input

I'm trying to draw a triangle in python using Matoplotlib with the sides sizes given from input. Below you will see my code, how can I take my variables and draw a triangle in Matplotlib with them?

import numpy as np
import turtle
from turtle import *
import matplotlib
matplotlib.use('TkAgg')
import matplotlib.pyplot as plt
import matplotlib.patches as patches



def triangle_angle(t, v, w):
    """Diese Funktion ergibt den Eck zwischen v und w"""

    cosT=np.divide((v**2+w**2-t**2),2*v*w)
    alfaT=np.arccos(cosT)
    alfaT=np.degrees(alfaT)
    return alfaT

def triangle(a,b,c):

    l=[]
    if (a+b>c) and (a+c>b) and (b+c>a) : #
        l.append(True)   
        l.append(np.sum([a,b,c]))
        p = float(np.divide(l[1], 2))       #Berechnet die haelfte des Umfangs
        l.append(np.sqrt(np.prod([p, (p - a), (p - b), (p - c)])))    #Berechnet die Flaeche mittles Heron Formula
    else:
        l.append(False)                     #Gibt dem ersten Element den Wert False
        l.append("Diese Zahlen koennen kein Dreieck konstruieren, Das Umfang koennte nicht berechnet sein")
        l.append("Die Flaeche koennte nicht berechnet sein") # Die Flaeche und Umfang koennte nicht berechnet werden
    return(l)

print("Dieses Programm prueft ob es mit 3 gegebene Laengen ein Dreickes gibt, berechnet \
 die Flaeche und das Umfang des Dreiecks und es zeichnet")

x=float(raw_input("geben Sie die erste Zahl ein  "))
y= float(raw_input("geben Sie die erste Zahl ein  "))
z= float(raw_input("geben Sie die erste Zahl ein  "))
if (x<=0) or (y<=0) or (z<=0):
    print("Eine oder mehrere Zahlen sind nicht positiv, bitte geben Sie die !Positive! Zahlen noch einmal. ")
    x=float(raw_input("geben Sie die erste Zahl ein  "))
    y= float(raw_input("geben Sie die erste Zahl ein  "))
    z= float(raw_input("geben Sie die erste Zahl ein  "))
    if triangle(x,y,z)[0] == True:
        print("So ein Dreiecks gibt es. Das Umfang ist "+str(triangle(x,y,z)[1])+" und die Flaeche ist "+str(triangle(x,y,z)[2]))
    else:
        print("So ein Dreiecks gibt es nicht")
else:
    if triangle(x,y,z)[0] == True:
        print("So ein Dreiecks gibt es. Das Umfang ist "+str(triangle(x,y,z)[1])+" und die Flaeche ist "+str(triangle(x,y,z)[2]))
    else:
        print("So ein Dreiecks gibt es nicht")



fig1 = plt.figure()
ax1 = fig1.add_subplot(111, aspect='equal')
ax1.add_patch(patches.RegularPolygon((0.5, 0.5),3,0.2,))
plt.show()

Any help will be appreciated, thanks.

Upvotes: 0

Views: 5469

Answers (1)

ImportanceOfBeingErnest
ImportanceOfBeingErnest

Reputation: 339170

A equilateral triangle can be plotted in matplotlib using a RegularPolygon. However, if the sides of the triangle may differ, this is not an option.

Therefore the triangle needs to be plotted as a general Polygon. One thus needs the coordinates of the edge points.

For simplicity we may choose to position the longest edge (c) along the x axis, which determines the first two points of the triangle as (0,0) and (c,0). What's left is to caclulate the coordinates of the triangle peak.

import numpy as np
import matplotlib.pyplot as plt

def calc_angles(a,b,c):
    alpha = np.arccos(  (b**2 + c**2 - a**2) /(2.*b*c) )
    beta = np.arccos(  (-b**2 + c**2 + a**2) /(2.*a*c) )
    gamma = np.pi-alpha-beta
    return alpha, beta, gamma

def calc_point(alpha, beta, c):
    x = (c*np.tan(beta) )/( np.tan(alpha)+np.tan(beta) )
    y = x * np.tan(alpha)
    return (x,y)

def get_triangle(a,b,c):
    z = np.array([a,b,c])
    while z[-1] != z.max():
        z = z[[2,0,1]] # make sure last entry is largest
    alpha, beta, _ = calc_angles(*z)
    x,y = calc_point(alpha, beta, z[-1])
    return [(0,0), (z[-1],0), (x,y)]

a = 4
b = 3
c = 2

fig, ax = plt.subplots()
ax.set_aspect("equal")

dreieck = plt.Polygon(get_triangle(a,b,c))
ax.add_patch(dreieck)
ax.relim()
ax.autoscale_view()
plt.show()

enter image description here

Upvotes: 2

Related Questions