Saltycrane logo

SaltyCrane Blog

Notes on Python, Django, and web development on Ubuntu Linux

    

How to create some derived arrow classes with matplotlib and python

Here is an example of how to create some derived arrow classes with matplotlib and python. The arrow() function in matplotlib accepts origin and delta x and delta y inputs. I changed this to polor coordinates so Arrow2 accepts the x and y coordinates of the origin, the length, and the angle. Then I created 4 classes derived from Arrow2 called ArrowRight, ArrowLeft, ArrowUp, and ArrowDown. These just set the angle for you to 0, 180, 90, and 270 respectively. Notice too that the **kwargs can be passed down so you can still set all the other parameters.
""" arrow_ex2.py """ 
from pylab import *  

def main(): 
    figure() 
    axes() 
    Arrow2(.5,.5,.2,45) 
    ArrowRight(.5,.5,.2) 
    ArrowLeft(.5,.5,.2) 
    ArrowUp(.5,.5,.2) 
    ArrowDown(.5,.5,.2) 
    show() 

class Arrow2: 
    def __init__(self, x0, y0, length, angle=0.0, color='k', width=0.01, **kwargs):          
        dx = length*cos(angle*pi/180) 
        dy = length*sin(angle*pi/180) 
        arrow (x0, y0, dx, dy, 
               width=width, 
               edgecolor=color,  
               facecolor=color,  
               antialiased=True,  
               head_width=5*width, 
               head_length=7.5*width, 
               **kwargs)

class ArrowRight(Arrow2): 
    def __init__(self, x0, y0, length, **kwargs): 
        Arrow2.__init__(self, x0, y0, length, angle=0.0, **kwargs)

class ArrowLeft(Arrow2): 
    def __init__(self, x0, y0, length, **kwargs): 
        Arrow2.__init__(self, x0, y0, length, angle=180.0, **kwargs)                      

class ArrowUp(Arrow2): 
    def __init__(self, x0, y0, length, **kwargs): 
        Arrow2.__init__(self, x0, y0, length, angle=90.0, **kwargs) 

class ArrowDown(Arrow2): 
    def __init__(self, x0, y0, length, **kwargs): 
        Arrow2.__init__(self, x0, y0, length, angle=270.0, **kwargs) 

if __name__ == "__main__": 
    main() 

Post a comment

Required
Required, but not displayed
Optional

Format using Markdown. (No HTML.)
  • Code blocks: prefix each line by at least 4 spaces or 1 tab (and a blank line before and after)
  • Code span: surround with backticks
  • Blockquotes: prefix lines to be quoted with >
  • Links: <URL>
  • Links w/ description: [description](URL)
Created with Django | Hosted by Slicehost