Friday, July 7, 2017

Plotting graphs with Python — Simple example

As plotting graphs is something that my oldest kid started doing in school, I decided to finally spend some time doing it in Python. This article is about the basics, but I will also later get into the calculations of medium, mean, mode and other more complex concepts of plotting graphs using mathematical formulas.
Here is an example that shows you the following:
  • * takes a list or more lists and plots it on the graph
  • * plotting of points on the graph with or without connecting it into lines
  • * applying the labels on the x-axis and y-axis
  • * applying the overall title on the graph
  • * adjusting your scale based on what type of data you have for each axis
Install the following libraries before running the code below. By the way, the example is written for Python 2.7.x:
pip install matplotlib
pip install matplotlib-venn
Here is the example that you can play with as it has a command-line menu that allows you to choose which type of graph you want:
__author__ = 'Almir Mustafic'


from pylab import plot, show, title, xlabel, ylabel
from pylab import legend
from pylab import axis


def main():
    print("main program")
    while True:
        print_menu()

        choice = raw_input('Pick from the menu? ')

        if choice == '1':
            plotting_example01()
        elif choice == '2':
            plotting_example02()
        elif choice == '3':
            plotting_example03()
        elif choice == '4':
            plotting_example04()
        elif choice == '5':
            plotting_example05()
        elif choice == '6':
            plotting_example06()
        elif choice == '7':
            plotting_example07()
        elif choice == 'q':
            break

        print("")

def print_menu():
    print("=========================================================================")
    print('1. Plot a few points WITHOUT dots for the given point and connect as line')
    print('2. Plot a few points WITH dots for the given point and connect as line')
    print('3. Plot a few points WITH dots and WITHOUT the LINE')
    print('4. Plot Ladera Ranch town temperature with DOTS and LINE and NO X-Axis specific range')
    print('5. Plot Ladera Ranch town temperature with DOTS and LINE and X-AXIS range specified')
    print('6. Plot Ladera Ranch averages in 1996, 2006 and 2016 for 12 months. 3 graphs')
    print('7. Plot Ladera Ranch averages - Adjust AXIS based on min and max')
    print("q. QUIT")
    print("=========================================================================")


def plotting_example01():
    print("Plotting example 1............")

    x_numbers = [1, 2, 3]
    y_numbers = [2, 4, 6]

    # Plot the line WITHOUT dots for the given points
    plot(x_numbers, y_numbers)
    show()


def plotting_example02():
    print("Plotting example 2............")

    x_numbers = [1, 2, 3]
    y_numbers = [2, 4, 6]

    # Plot the line WITH dots for the given points
    # Markers can be 'o' or '*' or 'x' or '+'
    plot(x_numbers, y_numbers, marker='o')
    show()


def plotting_example03():
    print("Plotting example 3............")

    x_numbers = [1, 2, 3]
    y_numbers = [2, 4, 6]

    # Plot the line WITH dots and WITHOUT LINE
    plot(x_numbers, y_numbers, 'o')
    show()


def plotting_example04():
    print("Plotting example 4............")

    ladera_temp = [53.9, 56.3, 56.4, 53.4, 54.5, 55.8, 56.8, 55.0, 55.3, 54.0, 56.7, 56.4, 57.3]

    # Plot the line WITH dots and the LINE
    plot(ladera_temp, marker='o')
    show()


def plotting_example05():
    print("Plotting example 5............")

    ladera_temp = [53.9, 56.3, 56.4, 53.4, 54.5, 55.8, 56.8, 55.0, 55.3, 54.0, 56.7, 56.4, 57.3]
    # years = range(2000, 2013)
    years = range(2000, len(ladera_temp) + 2000)

    # Plot the line WITH dots and the LINE
    plot(years, ladera_temp, marker='o')
    show()


def plotting_example06():
    print("Plotting example 6............")

    ladera_temp_1996 = [53.9, 56.3, 56.4, 53.4, 54.5, 55.8, 56.8, 55.0, 55.3, 54.0, 56.7, 56.4]
    ladera_temp_2006 = [43.9, 66.3, 46.4, 63.4, 34.5, 75.8, 46.8, 65.0, 75.3, 64.0, 56.7, 46.4]
    ladera_temp_2016 = [23.9, 26.3, 36.4, 33.4, 44.5, 55.8, 66.8, 75.0, 65.3, 54.0, 46.7, 36.4]

    months = range(1, 13)

    # Plot the line WITH dots and the LINE
    plot(months, ladera_temp_1996, months, ladera_temp_2006, months, ladera_temp_2016, marker='+')

    # OR you can plot separately like this and the final show() method will know that it needs to plot everything that is queued up.
    # plot(months, ladera_temp_1996, marker='o')
    # plot(months, ladera_temp_2006, marker='o')
    # plot(months, ladera_temp_2016, marker='o')

    # Apply the legend to tell the graphs apart
    legend([1996, 2006, 2016])

    # Apply the TITLE, X-axis and Y-axis label
    title('Average monthly temperature in Ladera Ranch town')
    xlabel('Month')
    ylabel('Temperature in F')

    show()


def plotting_example07():
    print("Plotting example 7............")

    ladera_temp_1996 = [53.9, 56.3, 56.4, 53.4, 54.5, 55.8, 56.8, 55.0, 55.3, 54.0, 56.7, 56.4]
    ladera_temp_2006 = [43.9, 66.3, 46.4, 63.4, 34.5, 75.8, 46.8, 65.0, 75.3, 64.0, 56.7, 46.4]
    ladera_temp_2016 = [23.9, 26.3, 36.4, 33.4, 44.5, 55.8, 66.8, 75.0, 65.3, 54.0, 46.7, 36.4]

    months = range(1, 13)

    # Plot the line WITH dots and the LINE
    plot(months, ladera_temp_1996, months, ladera_temp_2006, months, ladera_temp_2016, marker='+')

    # OR you can plot separately like this and the final show() method will know that it needs to plot everything that is queued up.
    # plot(months, ladera_temp_1996, marker='o')
    # plot(months, ladera_temp_2006, marker='o')
    # plot(months, ladera_temp_2016, marker='o')

    # Figure out AXIS X and Y min and max and set it for the graphs.
    print(axis())
    xy_tuple = axis()   # returns tuple (x-min, x-max, y-min, y-max)
    my_ymin = xy_tuple[2]
    axis(ymin=my_ymin-20)
    axis(xmax=xy_tuple[1]+6)

    # Another way to set X-min, X-max, y-min, y-max
    # axis([xy_tuple[0], xy_tuple[1], xy_tuple[2], xy_tuple[3]])

    # Apply the legend to tell the graphs apart
    legend([1996, 2006, 2016])

    # Apply the TITLE, X-axis and Y-axis label
    title('Average monthly temperature in Ladera Ranch town')
    xlabel('Month')
    ylabel('Temperature in F')

    show()


################################################

if __name__ == "__main__": main()
Here is the command-line menu that you should see when you run this Python code:

For example, if you select option 6 (graph that uses a lot features summarized above), then you will the following graph pop up:



If you select option 7, then you will see how the scaling on the graph is adjusted explicitly through code:






Almir Mustafic





No comments:

Post a Comment