Beispiel #1
0
def gen_bars(data, headers, datasets, methods):
    """
    Description:
    Inputs:
    Outputs:
    """
    width = 0.5
    x = np.arange(0, 16, 2)
    
    labels_x = datasets.copy()
    labels_x.insert(0,"") 
    
    fig, ax = plt.subplots()
    bar1 = ax.bar(x - (0.3 + width/2), data[0,:], width, label = methods[0])
    add_labels(ax, bar1)

    if (len(methods) > 1):
        bar2 = ax.bar(x , data[1,:], width, label = methods[1])
        add_labels(ax, bar2)
    
        if (len(methods) > 2):
            bar3 = ax.bar(x + (0.3 + width/2), data[1,:], width, label = methods[2])
            add_labels(ax, bar3)

    ax.set_ylabel(metric)
    ax.set_xlabel("Dataset")
    
    ax.set_xticklabels(labels_x)
    ax.set_title(metric + " Across Datasets")
    ax.legend(bbox_to_anchor=(1, 1.15), fancybox=True, framealpha=0.5)
 def allGraphs(self):
     colors = ['r', 'g', 'b', 'c', 'm', 'y', 'c']
     for f in range(len(self.features)):
         ax = plt.subplot(111)
         plt.xlabel('Standardized Feature Values')
         plt.ylabel('Probability')
         filename = self.resultsName + "_feature_" + str(
             self.features[f]) + "_std.png"
         title = "Histogram of feature: " + str(look.feat(self.features[f]))
         plt.title(title)
         plt.grid(True)
         for j in range(len(self.H_)):
             prob = self.H_[j][f][0]
             bins = self.H_[j][f][1]
             barBins = bins[0:-1]
             bw = barBins[1] - barBins[0]
             ax.bar(barBins,
                    prob,
                    width=bw,
                    facecolor=colors[j],
                    alpha=0.75,
                    label=look.classes(j))
         ax.legend(loc=0)
         plt.savefig(filename, bbox_inches='tight')
         plt.close()
Beispiel #3
0
    def plotBarMatplotlib(self, x_list, y_list, value, unit):
        figureTitle = "{} for {} to {}".format(value, x_list[0], x_list[-1])
        logging.debug("Plotting {}".format(figureTitle))
        output_file = "{}Plot.png".format(value.title().replace(' ', ''))

        df = pd.DataFrame({'date': x_list, value: y_list})

        # plot
        figure, axes = plt.subplots(figsize=(16, 6))
        axes.bar('date', value, data=df, color='mediumvioletred')
        plt.title(figureTitle)
        plt.xlabel('Date')
        plt.ylabel('{} ({})'.format(value, unit))

        plt.legend()
        plt.grid(axis='y')

        plt.xticks(self.date)
        logging.debug(plt.xticks())
        if unit == "*C":
            plt.ylim(0, 70)
        else:
            plt.ylim(0, 50)

        plt.savefig(output_file)
        plt.show()
Beispiel #4
0
def club_tags(unencoded_clubs_list):
    """
    Creates a bar graph showing of the number of occurrances of each possible club tag.
    
    By using a dictionary to count club tag occurrances, the function then creates a 
    matplotlib bar graph using numpy representations of the dictionary information.
    The graph is formatted and pushed as a Response type for view on the server.
    
    Returns:
    --------
    Response
        The graph
    """

    club_dict = {}
    for clubs in unencoded_clubs_list:
        for tag in clubs.get_category():
            if tag in club_dict:
                club_dict[tag] = club_dict[tag] + 1
            else:
                club_dict[tag] = 1
    x = np.zeros(len(club_dict))
    index_counter = 0
    for tag in club_dict:
        x[index_counter] = club_dict.get(tag)
        index_counter = index_counter + 1

    fig = plt.figure()
    ax = fig.add_subplot()
    bar = ax.bar(np.arange(len(club_dict)), x)
    labels = club_dict.keys()
    ax.set_xticks(np.arange(len(club_dict)))
    ax.set_xticklabels(labels, rotation='45', ha='right')
    ax.set_xlabel('Club Tags')
    ax.set_ylabel('Number of Occurrances')
    ax.set_title('Number of Club Tag Occurrances')
    for rect in bar:
        height = rect.get_height()
        ax.annotate('{}'.format(height),
                    xy=(rect.get_x() + rect.get_width() / 2, height),
                    xytext=(0, 3),
                    textcoords="offset points",
                    ha='center',
                    va='bottom')

    plt.tight_layout()
    output = io.BytesIO()
    FigureCanvas(fig).print_png(output)
    return Response(output.getvalue(), mimetype='image/png')
 def printPost(self, prob):
     colors = ['r', 'g', 'b', 'c', 'm', 'y', 'x']
     ax = plt.subplot(111)
     plt.xlabel("Class")
     plt.ylabel("Relative Likelihood")
     plt.title("Posterior Probability")
     plt.tick_params(axis='x',
                     which='both',
                     bottom='off',
                     top='off',
                     labelbottom='off')
     width = 5
     for i, p in enumerate(prob):
         ax.bar(i * width,
                p * 100,
                width=width,
                facecolor=colors[i],
                alpha=0.75,
                label=look.classes(i))
     ax.legend(loc=0)
     plt.savefig(self.resultsName + "Img_" + str(self.currentImage) +
                 "_Prob.png",
                 bbox_inches='tight')
     plt.close()
Beispiel #6
0
def clubs_per_user(user_list):
    """
    Creates a bar graph of the number of clubs per user. 
    
    Using a dictionary to gather each user's name and the number of club each 
    user is in, numpy representations of the data is used to create a matplotlib
    bar graph. The graph is then formatted and pushed for view on the server.
    
    Returns:
    --------
    Response
        The graph
    """
    user_club_dict = {}
    for user in user_list:
        name = user.get_user_name()
        user_club_dict[name] = len(user.get_user_clubs())

    x = np.zeros(len(user_club_dict))
    index_counter = 0
    for user in user_club_dict:
        x[index_counter] = user_club_dict.get(user)
        index_counter = index_counter + 1

    fig = plt.figure()
    ax = fig.add_subplot()
    bar = ax.bar(np.arange(len(user_club_dict)), x)
    labels = user_club_dict.keys()
    ax.set_xticks(np.arange(len(user_club_dict)))
    ax.set_xticklabels(labels, rotation='45', ha='right')
    ax.set_xlabel('User Name')
    ax.set_ylabel('Number of Clubs')
    ax.set_title('Number of Clubs per User')
    for rect in bar:
        height = rect.get_height()
        ax.annotate('{}'.format(height),
                    xy=(rect.get_x() + rect.get_width() / 2, height),
                    xytext=(0, 3),
                    textcoords="offset points",
                    ha='center',
                    va='bottom')

    plt.tight_layout()
    output = io.BytesIO()
    FigureCanvas(fig).print_png(output)
    return Response(output.getvalue(), mimetype='image/png')
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.axes as ax
import pylab

# change to proper directory
os.chdir('C:\Users\Matt\Desktop\Python Projects\Exploratory Data Analysis')

# load file, select proper date range, convert row to numeric dtypes
hpc = pd.read_csv('household_power_consumption.txt',
                  sep=';',
                  index_col=['Date'],
                  usecols=['Global_active_power', 'Date'])
hpc = hpc['1/2/2007':'2/2/2007'].convert_objects(convert_numeric=True)

# create plotting variables
y = pd.value_counts(hpc.Global_active_power,
                    bins=np.arange(0, 8, 0.5),
                    sort=False)
index = y.index

fig = plt.figure()
ax = fig.add_subplot(1, 1, 1)
ax.bar(index, y, width=0.5, color='r')
ax.set_xlabel('Global Active Power (kilowatts)')
ax.set_ylabel('Frequency')
ax.set_title('Global Active Power')
pylab.show()

# hpc[hpc['Global_active_power'] > 4]
# import needed libraries
import os
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.axes as ax
import pylab

# change to proper directory
os.chdir('C:\Users\Matt\Desktop\Python Projects\Exploratory Data Analysis')

# load file, select proper date range, convert row to numeric dtypes
hpc = pd.read_csv('household_power_consumption.txt', sep=';', index_col=['Date'], usecols=['Global_active_power', 'Date'])
hpc = hpc['1/2/2007':'2/2/2007'].convert_objects(convert_numeric=True)

# create plotting variables
y = pd.value_counts(hpc.Global_active_power, bins=np.arange(0, 8, 0.5), sort=False)
index = y.index

fig = plt.figure()
ax = fig.add_subplot(1, 1, 1)
ax.bar(index, y, width=0.5, color='r')
ax.set_xlabel('Global Active Power (kilowatts)')
ax.set_ylabel('Frequency')
ax.set_title('Global Active Power')
pylab.show()


# hpc[hpc['Global_active_power'] > 4]
Beispiel #9
0
def create_bar_graph(data=[[[1, 2], [10, 20]]],
                     semilog=False,
                     add_bar_labels=True,
                     title='Insert Fancy Title',
                     add_legend=False,
                     bar_colors=[],
                     legend_labels=[]):
    import matplotlib.patches as mpatches
    from collections import deque
    if not bar_colors:
        bar_color_deque = deque([
            '#1395ba', '#a2b86c', '#ebc844', '#f16c20', '#c02e1d', '#0d3c55',
            '#ecaa38', '#117899', '#d94e1f', '#5ca793', '#ef8b2c', '#0f5b78'
        ])
    else:
        bar_color_deque = deque(bar_colors)
    width = 0.33
    xs = data[0][0]
    legend_labels_queue = deque(legend_labels)
    handles = []
    if len(data) > 1:
        width = 0.33 * 2 / len(data)
        #plot comparison from multiple archives
        all_unique_x = {}
        for series in data:
            for size in series[0]:
                all_unique_x[size] = True
        ind = np.arange(len(all_unique_x.keys()))
        rect_refs = []
        fig, ax = plt.subplots()
        bar_shift = width / 2
        #plot individual bars to allow for sparse data plots
        for series in data:
            if len(series) > 2:
                label = series[2]
            color = bar_color_deque.popleft()
            if legend_labels:
                legend_label = legend_labels_queue.popleft()
            else:
                legend_label = label
            handles.append(mpatches.Patch(color=color, label=legend_label))
            index = 0
            labeled_yet = False
            for ex in sorted(all_unique_x.keys()):
                for i in range(0, len(series[0])):
                    if series[0][i] == ex:
                        if 'label' in locals() and not labeled_yet:
                            rects = ax.bar(index + bar_shift,
                                           series[1][i],
                                           width,
                                           color=color,
                                           label=label)
                            labeled_yet = True
                        else:
                            rects = ax.bar(index + bar_shift,
                                           series[1][i],
                                           width,
                                           color=color)
                        rect_refs.append(rects[0])
                        if add_bar_labels:
                            bar_label(ax, rects, semilog)
                index += 1
            bar_shift += width
        if semilog:
            ax.set_yscale('log')
        ax.set_xticks(ind + 0.59 - 0.045 * len(data))
        if add_legend:
            plt.legend(handles=handles, loc=2)
    else:
        color = bar_color_deque.popleft()
        ys = data[0][1]
        ind = np.arange(len(xs))
        fig, ax = plt.subplots()
        rects = ax.bar(ind + width, ys, color=color)
        ax.set_xticks(ind + width * 2)
        if semilog:
            ax.set_yscale('log')
        if add_bar_labels:
            bar_label(ax, rects, semilog)
    fig.set_size_inches(15, 8)
    ax.set_xticklabels(xs, rotation=0)
    ax.set_title(title)
    ax.set_xlabel("Object Size (Bytes)")
    ax.set_ylabel('MB/s')
    plt.show()
    plt.savefig('foo.png')
    return
Beispiel #10
0
    ax.ticklabel_format(style='plain')
    ax.axis([0, 2000000, 0, 180000000])
    plt.grid( linestyle='-', linewidth=1)
    for tick in ax.get_xticklabels():
        tick.set_rotation(55)
    #plt.show()
    pdf.savefig(bbox_inches='tight')
    plt.close()

with PdfPages('ImagenFantasma_x_tamaño.pdf') as pdf:
    #plt.figure(figsize=(7, 5))
    labels = 'ASM', 'O3', 'O2', 'O0'
    barValues = [resASM[7],resC3[7],resC2[7],resC0[7]]
    x = [1,2,3,4]
    fig, ax = plt.subplots()
    rects1 = ax.bar(x, barValues,0.7, label='')
    plt.ylabel('')
    plt.xlabel("Implementaciones")
    plt.ylabel("Ciclos de clock")
    plt.title("Imagen Fantasma 1600x1200")
    ax.ticklabel_format(style='plain')
    ax.set_xticks(x)
    ax.set_xticklabels(labels)
    plt.grid(linestyle='-', linewidth=1, axis='y')
    pdf.savefig(bbox_inches='tight')
    plt.close()

def calcularPorcentaje(asm, c):
    return int((asm*100)/c)

for i in range(0,8):