Plotting examples


# CS111 
# Some example charts for reference
# More details: http://matplotlib.org/api/pyplot_summary.html

import numpy as np
import matplotlib.pyplot as plt

def verticalBarChartExample():
    """It plots a simple vertical bar chart with three bars and provides
    labels of them.
    """
    # Example data
    counts = [5, 20, 12]
    candy  = ["skittles", "twizzlers", "m&ms"]

    position = range(len(counts)) # [0, 1, 2]

    # make this the first figure
    plt.figure(1) 
    # Graph
    #          x        y
    plt.bar(position, counts, width=0.5, color='green', align='center')

    # Decorate
    plt.xticks(position, candy) # x-axis labels
    plt.title('1. verticalBarChartExample: Candy votes')
    plt.show()

def horizontalBarChartExample():
    """It plots a simple horizontal bar chart with three bars and provides
    labels of them.
    """
    # Example data
    counts = [5, 20, 12]
    candy  = ["skittles","twizzlers","m&ms"]
    position = range(len(candy))

    # Graph
    # make this the second figure
    plt.figure(2) 
    plt.barh(position, counts, 0.5, align='center')

    # Decorate
    plt.yticks(position, candy) # y-axis label
    plt.title("2. horizontalBarChartExample: Candy Preferences")

    # Show the graph
    plt.show()

def plotExample():
    """It plots a line chart, where the data points are marked with blue 
    circles. It decorates the plot with ticks and labels.
    """
    # x axis: Months
    months = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12] # or: months = range(1,13)

    # y axis: Average Boston highs
    highs = [36, 39, 45, 56, 66, 76, 81, 80, 72, 61, 52, 41]

    # make this the third figure
    plt.figure(3) 
    # Set the axis
    plt.axis([min(months), max(months), min(highs), max(highs)])

    # Plot a line of points
    plt.plot(months, highs, 'bo-') # Markers: b=blue, o=circle, -=line

    # xticks
    monthNames = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec']
    plt.xticks(months, monthNames) # location, label

    # Decorate
    plt.xlabel('Months')
    plt.ylabel('Average highs')
    plt.title('3. plotExample: Average highs in Boston')
    plt.grid()

    # Show the graph
    plt.show()

def pieChartExample():
    """It plots a piechart with four slices.
    """
    # Data
    icecream = [30, 50, 10, 6] # Do not have to sum to 100
    mycolors = ['pink', 'chocolate', 'ivory','yellow']
    mylabels = ['Strawberry', 'Chocolate', 'Vanilla','Banana']

    # Graph `figsize` is needed so the pie won't be squished
    plt.figure(figsize=(5,5), facecolor='white') # new figure window
    plt.pie(icecream, labels=mylabels, colors=mycolors)

    # Decorate
    plt.title("4. pieChartExample: Ice Cream Preferences")

    # Show the graph
    plt.show()

# Tests
if __name__ == '__main__':
    verticalBarChartExample()
    horizontalBarChartExample()
    plotExample()
    pieChartExample()

Table of Contents