Python matplotlib.pyplot.barh() Examples

The following are code examples for showing how to use matplotlib.pyplot.barh(). They are from open source Python projects. You can vote up the examples you like or vote down the ones you don't like.

Example 1
Project: fc-aaai18   Author: thanhan   File: plot_all.py    MIT License 7 votes vote down vote up
def plot_survey2():

    
    import seaborn as sns
    import matplotlib.pyplot as plt
    import numpy as np
    colors = sns.color_palette('colorblind')
    a = [1,6,3,1,0]
    b = [0,4,3,5,0]
    
    
    plt.yticks( range(5), ['Very Disatisfied', 'Dissatisfied', 'Neutral', 'Satisfied', 'Very satisfied'])
    
    plt.xlabel('Number of users')
    
    p1 = plt.barh(np.arange(5)-0.15 , a, 0.30, color = colors[0],hatch = 'x')
    p2 = plt.barh(np.arange(5)+0.15 , b, 0.30, color = colors[1])    
    
    plt.legend((p1[0], p2[0]), ('Group 1: Only prediction', 'Group 2: With explanation'))
    
    plt.savefig('survey.pdf', bbox_inches = 'tight', pad_inches = 0.001, dpi = 300) 
Example 2
Project: Transfer-Learning   Author: DhavalThkkar   File: predict.py    MIT License 7 votes vote down vote up
def plot_preds(image, preds):
    """Displays image and the top-n predicted probabilities in a bar graph
    Args:
        image: PIL image
        preds: list of predicted labels and their probabilities
    """
    
    """# For Spyder
    plt.imshow(image)
    plt.axis('off')"""

    plt.figure()
    labels = ("cat", "dog")
    plt.barh([0, 1], preds, alpha=0.5)
    plt.yticks([0, 1], labels)
    plt.xlabel('Probability')
    plt.xlim(0,1.01)
    plt.tight_layout()
    plt.savefig('out.png') 
Example 3
Project: dlime_experiments   Author: rehmanzafar   File: explanation.py    MIT License 6 votes vote down vote up
def as_pyplot_figure(self, label=0, type='h', **kwargs):
        exp = self.as_list(label=label, **kwargs)
        fig = plt.figure()
        vals = [x[1] for x in exp]
        names = [x[0] for x in exp]
        vals.reverse()
        names.reverse()
        colors = ['green' if x > 0 else 'red' for x in vals]
        pos = np.arange(len(exp)) + .5
        if type == 'h':
            plt.barh(pos, vals, align='center', color=colors)
            plt.yticks(pos, names)
        else:
            plt.bar(pos, vals, align='center', color=colors)
            plt.xticks(pos, names, rotation=90)

        if self.mode == "classification":
            title = 'Local explanation for class %s' % self.class_names[label]
        else:
            title = 'Local explanation'
        plt.title(title)
        return fig, names 
Example 4
Project: oxfs   Author: RainMark   File: iozone_xls_to_graph.py    MIT License 6 votes vote down vote up
def draw_one(self, xls, title, color):
        title = '{} ({})'.format(title, xls.columns[0])
        column_a = xls[xls.columns[0]]
        column_c = xls[xls.columns[2]]

        ticks = [column_a[x] for x in range(3, 16)]
        kbps = [self.float2(column_c[x]) for x in range(3, 16)]
        plt.barh(range(16 - 3), kbps, height=0.2, color=color, alpha=0.8)
        plt.yticks(range(16 - 3), ticks)
        plt.xlim(0, max(kbps) * 1.2)
        plt.xlabel("Speed")
        plt.title(title)
        for x, y in enumerate(kbps):
            plt.text(y + 1000, x - 0.1, '%s KB/s' % y)

        plt.show() 
Example 5
Project: django-binder   Author: CodeYellowBV   File: analyze_logs.py    MIT License 6 votes vote down vote up
def plot(items, sort=None, title=None, left_margin=0.20):
	import matplotlib.pyplot as plt

	if sort == 'keys':
		items = sorted(items, key=itemgetter(0), reverse=True)
	if sort == 'values':
		items = sorted(items, key=itemgetter(1), reverse=True)
	keys, values = list(zip(*items))
	plt.figure()
	if title:
		plt.suptitle(title)
	plt.style.use('seaborn-darkgrid')
	plt.barh(list(range(len(keys))), values)
	plt.yticks(list(range(len(keys))), keys)
	plt.subplots_adjust(left=left_margin, right=0.98, top=0.98, bottom=0.04)
	plt.show(block=False) 
Example 6
Project: moonshot   Author: rpeloff   File: keywords.py    MIT License 6 votes vote down vote up
def plot_keyword_count_distribution(keywords_set, output_dir, filename):
    """TODO(rpeloff) document and move to plotting (?)"""
    import os
    import matplotlib.pyplot as plt
    from moonshot.utils import plotting

    unique_keywords, keyword_counts = get_unique_keywords_counts(keywords_set)

    plt.figure(figsize=(12, len(keyword_counts) * 0.2))
    plt.barh(
        unique_keywords[np.argsort(keyword_counts)], keyword_counts[np.argsort(keyword_counts)])
    plt.title("Unique Keyword Occurences")

    plotting.save_figure(filename, path=output_dir, tight_layout=True)


# TODO(rpeloff) complete function 
Example 7
Project: osm-data-classification   Author: Oslandia   File: unsupervised_learning.py    MIT License 6 votes vote down vote up
def contrib_barplot(data, best=10):
    """Highlight best PCA contributors (either features or individuals), by
    considering the contribution sum of squares, in the chosen PCA

    Parameters
    ----------
    data: pandas.DataFrame
        data to plot
    best: integer
        number of contributors (features or individuals) to highlight, default
    to 10
    
    """
    contribs = data.apply(lambda x: sum(x**2), axis=1).sort_values().tail(best)
    plt.barh(np.arange(best), contribs.values, tick_label=contribs.index)
    plt.tight_layout()
    plt.show() 
Example 8
Project: DataExploration   Author: AdmiralWen   File: ModelVisuals.py    MIT License 6 votes vote down vote up
def rfFeatureImportance(data_X, rf_model, sns_font_scale = 2):
	'''
		Feature importance graph for random forest models. Use the sns_font_scale argument to scale the font size.
		
		data_X: the matrix of explanatory variables used as the input of the random forest model (the "X" matrix)
		rf_model: the random forest model object
	'''
	sns.set(font_scale = sns_font_scale)
	features_list = data_X.columns.values
	feature_importance = rf_model.feature_importances_
	feature_importance = 100 * (feature_importance/feature_importance.max())

	sorted_idx = np.argsort(feature_importance)

	pos = np.arange(sorted_idx.shape[0])
	plt.barh(pos, feature_importance[sorted_idx], align='center')
	plt.yticks(pos, features_list[sorted_idx])
	plt.xlabel('Relative Importance')
	plt.title('Random Forest Variable Importance')
	plt.show() 
Example 9
Project: API-Manager   Author: OpenBankProject   File: views.py    GNU Affero General Public License v3.0 6 votes vote down vote up
def plot_bar_chart(self, data):
        x = []
        y = []
        for item in data:
            y.append(item['count'])
            x.append(item['Implemented_by_partial_function'])
        plt.barh(x, y)
        plt.title("Top apis", fontsize=10)
        plt.xlabel("Number of API Calls", fontsize=8)
        plt.xticks([])
        plt.ylabel("Partial function", fontsize=8)
        plt.tick_params(axis='y', labelsize=8)
        for i, j in zip(y, x):
            plt.text(i, j, str(i), clip_on=True, ha='center',va='center', fontsize=8)
        plt.tight_layout()
        buf = BytesIO()
        plt.savefig(buf, format='png')
        image_base64 = base64.b64encode(buf.getvalue()).decode('utf-8').replace('\n', '')
        buf.close()
        # Clear the previous plot.
        plt.gcf().clear()
        return image_base64 
Example 10
Project: report-python-docx   Author: kleberandrade   File: beta_report_send_email.py    MIT License 6 votes vote down vote up
def plot_bar_err(filename, data, legends):
    
    x_pos = [i for i, _ in enumerate(legends)]
    average = [None] * len(x_pos)
    variance = [None] * len(x_pos)
    
    for i in x_pos:
        average[i] = np.mean(data[i])
        variance[i] = np.std(data[i])
        
    print("[{}] Média: {} - ({})".format(filename, average, np.average(average)))
        
    plt.barh(x_pos, average, color='steelblue', xerr=variance)
    
    plt.yticks(x_pos, legends, fontsize=12)
    plt.xticks(list(range(11)), fontsize=12)
    
    plt.xlabel('Nota')
    
    plt.savefig(filename + '_bar_err.png', bbox_inches='tight', dpi=400)    
    plt.show()
    plt.close() 
Example 11
Project: geospatial-learn   Author: Ciaran1981   File: learning.py    GNU General Public License v3.0 6 votes vote down vote up
def plot_feature_importances(modelPth, featureNames):
    
    """
    Plot the feature importances of an ensemble classifier
    
    Parameters
    --------------------------
    
    modelPth : string
               A sklearn model path 
    
    featureNames : list of strings
                   a list of feature names
    
    """
    
    model = joblib.load(modelPth)
    
    n_features = model.n_features_
    plt.barh(range(n_features), model.feature_importances_, align='center')
    plt.yticks(np.arange(n_features), featureNames)
    plt.xlabel("Feature importance")
    plt.ylabel("Feature")
    plt.ylim(-1, n_features)
    plt.show() 
Example 12
Project: brain-segmentation-pytorch   Author: mateuszbuda   File: inference.py    MIT License 6 votes vote down vote up
def plot_dsc(dsc_dist):
    y_positions = np.arange(len(dsc_dist))
    dsc_dist = sorted(dsc_dist.items(), key=lambda x: x[1])
    values = [x[1] for x in dsc_dist]
    labels = [x[0] for x in dsc_dist]
    labels = ["_".join(l.split("_")[1:-1]) for l in labels]
    fig = plt.figure(figsize=(12, 8))
    canvas = FigureCanvasAgg(fig)
    plt.barh(y_positions, values, align="center", color="skyblue")
    plt.yticks(y_positions, labels)
    plt.xticks(np.arange(0.0, 1.0, 0.1))
    plt.xlim([0.0, 1.0])
    plt.gca().axvline(np.mean(values), color="tomato", linewidth=2)
    plt.gca().axvline(np.median(values), color="forestgreen", linewidth=2)
    plt.xlabel("Dice coefficient", fontsize="x-large")
    plt.gca().xaxis.grid(color="silver", alpha=0.5, linestyle="--", linewidth=1)
    plt.tight_layout()
    canvas.draw()
    plt.close()
    s, (width, height) = canvas.print_to_buffer()
    return np.fromstring(s, np.uint8).reshape((height, width, 4)) 
Example 13
Project: hack-lastfm   Author: CSEC-NITH   File: utils.py    MIT License 6 votes vote down vote up
def comparison_graph(N,freq1,freq2,new_list,user1,user2):
    ind = np.arange(N)  # the x locations for the groups
    width = 0.25       # the width of the bars

    fig, ax = plt.subplots(figsize=(25, 10))
    rects1 = ax.barh(ind, freq1, width, color='#9DB9AE')
    rects2 = ax.barh(ind + width, freq2, width, color='#645D56')
    t = ()
    for i in new_list:
        t = t+(i,)
    # add some text for labels, title and axes ticks
    ax.set_xlabel('Play Count')
    ax.set_title('Top common artists')
    ax.set_yticks(ind + width / 2)
    ax.set_yticklabels(t)

    ax.legend((rects1[0], rects2[0]), (user1, user2))

    plt.savefig('static/'+ user1+user2+'.jpg') 
Example 14
Project: URPHelper   Author: mayongze   File: DataAnalysis.py    Apache License 2.0 6 votes vote down vote up
def flunkCourseRank_barh():
    strSql = "SELECT course.c_name,count(g.grade) FROM grade AS g,course WHERE g.semester = '2016-2017-2' AND g.flunkcount > 0 AND g.cno = course.c_no GROUP BY course.c_name ORDER BY count(g.cno) DESC"
    tmp = dbHepler.fetchall(strSql)
    courseList,grade = [],[]
    for item in tmp:
        #if int(item[1]) > 5:
        courseList.append(item[0])
        grade.append(item[1])

    label = courseList
    x = grade
 
    idx = np.arange(len(x))
    color = cm.jet(np.array(x)/max(x))
    plt.barh(idx, x, color=color)
    #plt.yticks(idx+1,label)

    plt.yticks(idx,label,fontsize=5)
    plt.grid(axis='x')
 
    plt.xlabel('不及格人数')
    plt.ylabel('科目')
    plt.title('2016-2017 春季学期 不及格科目')
 
    plt.show() 
Example 15
Project: Cookbook   Author: JeffMacaluso   File: MachineLearning-Master.py    MIT License 6 votes vote down vote up
def feature_importance(model):
    '''
    Plots the feature importance for an ensemble model
    '''
    feature_importance = model.feature_importances_
    feature_importance = 100.0 * (feature_importance / feature_importance.max())
    sorted_idx = np.argsort(feature_importance)
    pos = np.arange(sorted_idx.shape[0]) + .5
    plt.figure(figsize=(15, 15))
    plt.subplot(1, 2, 2)
    plt.barh(pos, feature_importance[sorted_idx], align='center')
    plt.yticks(pos, X.columns[sorted_idx])
    plt.xlabel('Relative Importance')
    plt.title('Variable Importance')
    plt.show()
    
#################################################################################################################
##### Misc

# Prediction Intervals - Ensemble Scikit-Learn Models 
Example 16
Project: gantt   Author: stefanSchinkel   File: gantt.py    MIT License 6 votes vote down vote up
def render(self):
        """ Prepare data for plotting
        """

        # init figure
        self.fig, self.ax = plt.subplots()
        self.ax.yaxis.grid(False)
        self.ax.xaxis.grid(True)

        # assemble colors
        colors = []
        for pkg in self.packages:
            colors.append(pkg.color)

        self.barlist = plt.barh(self.yPos, list(self.durations),
                                left=self.start,
                                align='center',
                                height=.5,
                                alpha=1,
                                color=colors)

        # format plot
        self.format()
        self.add_milestones()
        self.add_legend() 
Example 17
Project: ocr   Author: prasunroy   File: scan.py    MIT License 6 votes vote down vote up
def plot_hist(accu_rows, accu_cols_list):
    pyplot.figure()
    pyplot.title('Horizontal Scan')
    pyplot.xlabel('Frequency')
    pyplot.ylabel('Row')
    pyplot.gca().invert_yaxis()
    pyplot.barh(range(len(accu_rows)), accu_rows)
    
    line = 0
    
    for accu_cols in accu_cols_list:
        pyplot.figure()
        pyplot.title('Vertical Scan of Line {}'.format(line))
        pyplot.xlabel('Column')
        pyplot.ylabel('Frequency')
        pyplot.bar(range(len(accu_cols)), accu_cols)
    
    pyplot.show()
    
    return


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

# scan image by histogram 
Example 18
Project: DisplaceNet   Author: GKalliatakis   File: hra_utils.py    MIT License 5 votes vote down vote up
def plot_preds(violation_class, image, preds):
  """Displays image and the top-n predicted probabilities in a bar graph.

  # Arguments
    violation_class: violation_class: one of `cl` (HRA dataset with 2 classes - [i]'child_labour' and [ii]'no violation')
        or `dp` (HRA dataset with 2 classes - [i]'displaced_populations' and [ii]'no violation')
    image: PIL image
    preds: list of predicted labels and their probabilities
  """

  if violation_class == 'cl':
      labels = ("Child Labour", "NO Child Labour")

  elif violation_class == 'dp':
      labels = ("Displaced Populations", "NO Displaced Populations")



  order = list(reversed(range(len(preds))))
  plt.imshow(image)
  plt.axis('off')

  # fig = plt.figure(figsize=(2, 2))
  #
  # fig.add_subplot(1, 1, 1)
  # plt.imshow(image)
  #
  # fig.add_subplot(2, 2, 2)
  # plt.barh(order, preds, alpha=0.55)


  plt.figure()
  plt.barh(order, preds, alpha=0.55)
  plt.yticks(order, labels)
  plt.xlabel('Probability')
  plt.xlim(0,1.01)
  plt.tight_layout()
  plt.show() 
Example 19
Project: housebot   Author: jbkopecky   File: utils.py    MIT License 5 votes vote down vote up
def plot_compare_feature_levels(data):
    # [(name, value), (name, value) ....]
    ra = range(len(data))
    plt.barh(ra, [x[1] for x in data], align='center', alpha=0.4)
    plt.yticks(ra, [x[0] for x in data]) 
Example 20
Project: pennai   Author: EpistasisLab   File: skl_utils.py    GNU General Public License v3.0 5 votes vote down vote up
def plot_imp_score(tmpdir, _id, coefs, feature_names, imp_score_type):
    """Plot importance scores for features.
    Parameters
    ----------
    tmpdir: string
        Temporary directory for saving experiment results
    _id: string
        Experiment ID in PennAI
    coefs: array
        Feature importance scores
    feature_names: np.array
        List of feature names
    imp_score_type: string
        Importance score type

    Returns
    -------
    top_features: list
        Top features with high importance score
    indices: ndarray
        Array of indices of top important features

    """
    # plot bar charts for top important features
    num_bar = min(max_bar_num, len(coefs))
    indices = np.argsort(coefs)[-num_bar:]
    h=plt.figure()
    plt.title(imp_score_type)
    plt.barh(range(num_bar), coefs[indices], color="r", align="center")
    top_features = list(feature_names[indices])
    plt.yticks(range(num_bar), feature_names[indices])
    plt.ylim([-1, num_bar])
    h.tight_layout()
    plt.savefig(tmpdir + _id + '/imp_score' + _id + '.png')
    plt.close()
    return top_features, indices 
Example 21
Project: fanalysis   Author: OlivierGarciaDev   File: base.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def plot_row_cos2(self, num_axis, nb_values=None, figsize=None):
        """ Plot the row cosines graph
            
        For the selected axis, the graph represents the row cosines
        sorted in descending order.            
        
        Parameters
        ----------
        num_axis : int
            Select the axis for which the row cosines are plotted.
        
        nb_values : int
             Set the maximum number of values to plot.
             If nb_values is None : all the values are plotted.
        
        figsize : tuple of integers or None
            Width, height of the figure in inches.
            If not provided, defaults to rc figure.figsize
        
        Returns
        -------
        None
        """
        plt.figure(figsize=figsize)
        n_rows = len(self.row_labels_)
        n_labels = len(self.row_labels_)
        if (nb_values is not None) and (nb_values < n_labels):
            n_labels = nb_values
        limit = n_rows - n_labels
        cos2 = self.row_cos2_[:, num_axis - 1]
        cos2_sorted = np.sort(cos2)[limit:n_rows]
        labels = pd.Series(self.row_labels_)[np.argsort(cos2)][limit:n_rows]
        r = range(n_labels)
        bar_width = 0.5
        plt.yticks([ri + bar_width / 2 for ri in r], labels)
        plt.barh(r, cos2_sorted, height=bar_width, color="steelblue",
                 align="edge")
        plt.title("Rows cos2")
        plt.xlabel("Cos2")
        plt.ylabel("Rows")
        plt.show() 
Example 22
Project: open-images-starter   Author: krinj   File: cmd_sample_analysis.py    MIT License 5 votes vote down vote up
def display_stats(instances: Dict[str, int],
                  title: str="SOMETHING",
                  file_name: str="graph_name",
                  n_display: int = 20):

    sorted_instances = sorted(instances.items(), key=lambda kv: kv[1])
    sorted_instances.reverse()

    Logger.log_special(title, with_gap=True)
    for i in range(n_display):
        Logger.log_field(loader.get_label(sorted_instances[i][0]).upper(), sorted_instances[i][1])

    # Create the figure.
    plt.style.use("ggplot")
    fig, ax = plt.subplots(figsize=(15, 8))
    short_instances = sorted_instances[:n_display]

    # Labels.
    y_label = [loader.get_label(s[0]) for s in short_instances]
    y_label.insert(0, "(OTHERS)")
    y = np.arange(len(y_label))

    # Values.
    x = [s[1] for s in short_instances]
    x.insert(0, sum([s[1] for s in sorted_instances[n_display:]]))
    c_map = plt.get_cmap("plasma")
    colors = c_map(1 - y / len(y))
    colors[0] = (0.7, 0.7, 0.7, 1.0)

    # Plot the graph.
    plt.barh(y, x, height=0.5, color=colors)
    ax.set_yticks(y)
    ax.set_yticklabels(y_label)
    ax.invert_yaxis()
    ax.set_title(f"{title}: ({len(samples)} Images)")
    ax.set_xlabel("Count")
    ax.set_ylabel("Class Name")
    plt.savefig(f"{settings.OUTPUT_DIRECTORY}/{file_name}.png")
    plt.clf() 
Example 23
Project: fc-aaai18   Author: thanhan   File: models.py    MIT License 5 votes vote down vote up
def plot_probs(probs, reps, ss, vera, save_name = 'abc.pdf'):
    import matplotlib
    #matplotlib.rcParams['pdf.fonttype'] = 42
    import matplotlib.pyplot as plt
    from matplotlib import gridspec
    import seaborn as sns
    
    colors = sns.color_palette('colorblind')
    
    probs = np.asarray(probs)
    reps = np.asarray(reps)
    
    m = len(probs)
    for i in range(m):
        if ss[i].startswith('www.'):
            ss[i] = ss[i][4:]
    
    plt.figure(figsize=(8,2.0))
    
    gs = gridspec.GridSpec(1, 2, width_ratios=[2.8, 1])
    
    plt.subplot(gs[1]) 
    plt.ylabel('Claim Vera. Prob.')
    plt.bar(range(3), vera, color = colors[3])
    plt.xticks(range(3), ['False', 'Unk.', 'True'])
    
    plt.subplot(gs[0]) 
    plt.xlabel('Source Reputation')
    plt.yticks( np.arange(m) + 0.0, ss)
    
    p1 = plt.barh(range(m), reps * probs[:, 0], color = colors[0], hatch = '//')
    p2 = plt.barh(range(m), reps * probs[:, 1], left = reps * probs[:, 0], color = colors[1])
    p3 = plt.barh(range(m), reps * probs[:, 2], left = reps * probs[:, 0] \
                  + reps * probs[:, 1], color = colors[2], hatch = '\\\\')
    
    
    plt.legend((p1[0], p2[0], p3[0]), ('Against', 'Observing', 'For'), \
               bbox_to_anchor=(0.2, 1.001, 0.5, 0.01), ncol = 3)
    
    plt.savefig(save_name, bbox_inches = 'tight', pad_inches = 0.001, dpi = 300) 
Example 24
Project: DOVE   Author: kiharalab   File: Show.py    GNU General Public License v3.0 5 votes vote down vote up
def draw_bar(labels,quants,indicate_path,xlabel,ylabel,title):
    width=0.35
    plt.figure(figsize=(8,(width+0.1)*len(quants)), dpi=300)
    # Bar Plot
    plt.cla()
    plt.clf()
    plt.barh(range(len(quants)),quants,tick_label=labels)
    plt.grid(True)
    plt.title(title)
    plt.xlabel(xlabel)
    plt.ylabel(ylabel)
    plt.savefig(indicate_path)
    plt.close() 
Example 25
Project: bundle   Author: davidbrochart   File: fpga_dashboard.py    MIT License 5 votes vote down vote up
def show(self):
        plt.figure(figsize=(16, 5))
        for i, colors in enumerate(self.bar['c']):
            b = plt.barh(range(self.opnb, 0, -1), [self.bar['t1'][i] - self.bar['t0'][i]] * self.opnb, left=self.bar['t0'][i])
            for j, c in enumerate(colors):
                b[j].set_color(c) 
Example 26
Project: bundle   Author: davidbrochart   File: cpu_dashboard.py    MIT License 5 votes vote down vote up
def show(self):
        plt.figure(figsize=(16, 5))
        for i, colors in enumerate(self.bar['c']):
            b = plt.barh(range(self.thread_nb), [self.bar['t1'][i] - self.bar['t0'][i]] * self.thread_nb, left=self.bar['t0'][i])
            for j, c in enumerate(colors):
                b[j].set_color(c)
        plt.show() 
Example 27
Project: dlime_experiments   Author: rehmanzafar   File: explanation.py    MIT License 5 votes vote down vote up
def as_pyplot_to_figure(self, type='h', name = None, label='0', lp=None, **kwargs):
        if label == '0':
            exp = self.as_list_zero(label=0, **kwargs)
        else:
            exp = self.as_list_one(label=1, **kwargs)
        vals = [x[1] for x in exp]
        names = [x[0] for x in exp]
        vals.reverse()
        names.reverse()
        colors = ['green' if x > 0 else 'red' for x in vals]
        #pos = np.arange(len(exp)) + .2
        pos = np.arange(len(exp)) / 3

        fig = plt.figure(figsize=(4, 2))
        if type == 'h':
            plt.barh(pos, vals, align='center', color=colors, height=0.2)
            plt.yticks(pos, names)
        else:
            plt.bar(pos, vals, align='center', color=colors)
            plt.xticks(pos, names, rotation=90)

        if self.mode == "classification":
            title = 'Local explanation for class: %s' % self.class_names[int(label)]
        else:
            title = 'Local explanation'
        plt.title(title)
        #plt.suptitle('Sup title', y=1.05, fontsize=18)
        #plt.savefig(str(name) + ".png")
        filename= 'results/' + str(name)+".pdf"
        plt.savefig(filename, bbox_inches='tight')
        return fig, names 
Example 28
Project: oxfs   Author: RainMark   File: iozone_xls_to_graph.py    MIT License 5 votes vote down vote up
def draw_compare(self):
        xls = self.oxfs_xls
        column_a = xls[xls.columns[0]]
        column_c = xls[xls.columns[2]]

        oxfs_ticks = [column_a[x] + '- oxfs' for x in range(3, 16)]
        oxfs_kbps = [self.float2(column_c[x]) for x in range(3, 16)]

        xls = self.sshfs_xls
        column_a = xls[xls.columns[0]]
        column_c = xls[xls.columns[2]]

        sshfs_ticks = [column_a[x] + '- sshfs' for x in range(3, 16)]
        sshfs_kbps = [self.float2(column_c[x]) for x in range(3, 16)]

        ticks = []
        kbps = []
        for i in range(0, len(oxfs_kbps)):
            ticks.append(oxfs_ticks[i])
            ticks.append(sshfs_ticks[i])
            kbps.append(oxfs_kbps[i])
            kbps.append(sshfs_kbps[i])

        barlist = plt.barh(range(len(kbps)), kbps, height=0.3, color='coral', alpha=0.8)
        for bar in barlist[1::2]:
            bar.set_color('slateblue')
        plt.yticks(range(len(ticks)), ticks)
        plt.xlim(0, max(kbps) * 1.2)
        for x, y in enumerate(kbps):
            plt.text(y + 1000, x - 0.1, '%s KB/s' % y)

        title = 'Oxfs Vs Sshfs ({})'.format(xls.columns[0])
        plt.title(title)
        plt.xlabel("Speed")

        plt.show() 
Example 29
Project: virginia-court-data-analysis   Author: bschoenfeld   File: speeding_vs_miles_driven.py    MIT License 5 votes vote down vote up
def chart_count(traffic_by_court, field, title, x_label, filename):
    traffic_by_court.sort(key=lambda x: x[field])

    plt.clf()

    plt.title(title)
    plt.xlabel(x_label)

    rects = plt.barh(
        range(len(traffic_by_court)),
        [x[field] for x in traffic_by_court],
        tick_label=[x['localityNames'] for x in traffic_by_court])

    xlim_max = plt.gca().get_xlim()[1]
    base_unit = int(xlim_max * 0.005)
    under_margin = int(xlim_max * 0.1)

    for rect in rects:
        width = rect.get_width()
        position = width - base_unit
        horizontal_align = 'right'
        color = 'white'
        if width < under_margin:
            # Set the value inside the bar if its over margin
            position = width + base_unit # pad the value
            horizontal_align = 'left'
            color = 'gray'
        plt.text(position, rect.get_y(),
                 '%d' % width,
                 va='bottom', ha=horizontal_align, color=color)

    plt.gca().set_ylim(-1, len(rects))
    plt.tight_layout()
    plt.savefig(filename) 
Example 30
Project: tieba-zhuaqu   Author: ankanch   File: graphicsData.py    GNU General Public License v3.0 5 votes vote down vote up
def barHonGraphics(xLabel,yLabel,xValueList,yValueList,graphicTitle='图例',xWidth=0.5):
    plt.barh(numpy.arange(len(xValueList)), yValueList, alpha=0.4)
    plt.yticks(numpy.arange(len(xValueList)), xValueList,fontproperties=font_set)
    plt.xlabel(yLabel,fontproperties=font_set)
    plt.ylabel(xLabel,fontproperties=font_set)
    plt.title(graphicTitle,fontproperties=font_set)

    plt.show()
	
#折线图:蓝色粗线 
Example 31
Project: tieba-zhuaqu   Author: ankanch   File: graphicsData.py    GNU General Public License v3.0 5 votes vote down vote up
def barHonGraphics(xLabel,yLabel,xValueList,yValueList,graphicTitle='图例',xWidth=0.5):
    plt.barh(numpy.arange(len(xValueList)), yValueList, alpha=0.4)
    plt.yticks(numpy.arange(len(xValueList)), xValueList,fontproperties=font_set)
    plt.xlabel(yLabel,fontproperties=font_set)
    plt.ylabel(xLabel,fontproperties=font_set)
    plt.title(graphicTitle,fontproperties=font_set)

    plt.show()
	
#折线图:蓝色粗线 
Example 32
Project: tieba-zhuaqu   Author: ankanch   File: graphicsData.py    GNU General Public License v3.0 5 votes vote down vote up
def barHonGraphics(xLabel,yLabel,xValueList,yValueList,graphicTitle='图例',xWidth=0.5):
    plt.barh(numpy.arange(len(xValueList)), yValueList, alpha=0.4)
    plt.yticks(numpy.arange(len(xValueList)), xValueList,fontproperties=font_set)
    plt.xlabel(yLabel,fontproperties=font_set)
    plt.ylabel(xLabel,fontproperties=font_set)
    plt.title(graphicTitle,fontproperties=font_set)

    plt.show()
	
#折线图:蓝色粗线 
Example 33
Project: tieba-zhuaqu   Author: ankanch   File: graphicsData.py    GNU General Public License v3.0 5 votes vote down vote up
def barHonGraphics(xLabel,yLabel,xValueList,yValueList,graphicTitle='图例',xWidth=0.5):
    plt.barh(numpy.arange(len(xValueList)), yValueList, alpha=0.4)
    plt.yticks(numpy.arange(len(xValueList)), xValueList,fontproperties=font_set)
    plt.xlabel(yLabel,fontproperties=font_set)
    plt.ylabel(xLabel,fontproperties=font_set)
    plt.title(graphicTitle,fontproperties=font_set)

    plt.show()
	
#折线图:蓝色粗线 
Example 34
Project: chanalyze   Author: itzmeanjan   File: util.py    MIT License 5 votes vote down vote up
def plotContributionInChatByUser(chat: Chat, targetPath: str, title: str, top: int = 25) -> bool:
    try:
        # considering only top 25 contributors in Chat
        y = reduce(lambda acc, cur: acc + [cur] if len(acc) < (top+1) else acc,
                   sorted([i.name for i in chat.users],
                          key=lambda e: len(chat.getUser(e).messages),
                          reverse=True),
                   [])
        # y = sorted([i.name for i in chat.users],
        #           key=lambda e: len(chat.getUser(e).messages), reverse=True)
        y_pos = range(len(y))
        x = [len(chat.getUser(i).messages)/chat.messageCount*100 for i in y]
        # y = [shadeContactName(i, percent=75) for i in y]
        with plt.style.context('Solarize_Light2'):
            font = {
                'family': 'serif',
                'color': '#000000',
                'weight': 'normal',
                'size': 10
            }
            plt.figure(figsize=(24, 12), dpi=100)
            plt.xlim((0, 100))
            plt.gca().xaxis.set_major_locator(MultipleLocator(10))
            plt.gca().xaxis.set_major_formatter(PercentFormatter())
            plt.gca().xaxis.set_minor_locator(MultipleLocator(1))
            plt.barh(y_pos, x, align='center',
                     color='deepskyblue', lw=1.6)
            plt.gca().yaxis.set_ticks(y_pos)
            plt.gca().yaxis.set_ticklabels(y)
            plt.xlabel('Percentage of Participation in Chat',
                       fontdict=font, labelpad=12)
            plt.title(title,
                      fontdict=font, pad=12)
            plt.tight_layout()
            plt.savefig(targetPath, bbox_inches='tight', pad_inches=.5)
            plt.close()
        return True
    except Exception:
        return False 
Example 35
Project: swift-code-metrics   Author: matsoftware   File: _graphics.py    MIT License 5 votes vote down vote up
def bar_plot(self, title, data):
        plt.title(title)
        plt.ylabel(title)
        opacity = 0.8
        _ = plt.barh(data[1], data[0], color='blue', alpha=opacity)
        index = np.arange(len(data[1]))
        plt.yticks(index, data[1], fontsize=5, rotation=30)
        self.__render(plt, title) 
Example 36
Project: bartpy   Author: JakeColtman   File: features.py    MIT License 5 votes vote down vote up
def plot_feature_split_proportions(model: SklearnModel, ax=None):
    if ax is None:
        fig, ax = plt.subplots(1, 1)
    proportions = feature_split_proportions(model)

    y_pos = np.arange(len(proportions))
    name, count = list(proportions.keys()), list(proportions.values())

    plt.barh(y_pos, count, align='center', alpha=0.5)
    plt.yticks(y_pos, name)
    plt.xlabel('Proportion of all splits')
    plt.ylabel('Feature')
    plt.title('Proportion of Splits Made on Each Variable')
    return ax 
Example 37
Project: hyperchamber   Author: HyperGAN   File: acceptance_io.py    MIT License 5 votes vote down vote up
def test_graph(config, filename, n):
  plt.rcdefaults()

  people = ('Tom', 'Dick', 'Harry', 'Slim', 'Jim')
  y_pos = np.arange(len(people))
  performance = 3 + 10 * np.random.rand(len(people))
  error = np.random.rand(len(people))

  plt.barh(y_pos, performance, xerr=error, align='center', alpha=0.4)
  plt.yticks(y_pos, people)
  plt.xlabel("Step "+str(n))
  plt.title('Are samples measurements working?')

  plt.savefig(filename) 
Example 38
Project: big-data-analytics   Author: PacktPublishing   File: JupyterNotebook.py    MIT License 5 votes vote down vote up
def plot(counts):
    labels = map(lambda x: x[0], counts)
    values = map(lambda y: y[1], counts)
    plt.barh(range(len(values)), values, color='green')
    plt.yticks(range(len(values)), labels)
    plt.show() 
Example 39
Project: GenEpi   Author: Chester75321   File: vcf2plot.py    MIT License 5 votes vote down vote up
def DrawClassificationPlot(df_variant, df_data, str_outputFilePath):
    ### count the number of mutations in each variant
    df_data = df_data.groupby(["order", "variant_ID_x", "phenotype"])["allele_type"].sum().unstack(fill_value=0).reset_index()
    ### draw barplot plot for dualistic phenotype
    float_barwidth = 0.35
    float_opacity = 0.8
    fig, ax = plt.subplots(1, 1, figsize=(15, 40))
    plt.barh(df_data["order"] + float_barwidth * 0.5, df_data.iloc[:,-1], float_barwidth, alpha=float_opacity, color="#CC2900", label='Case')
    plt.barh(df_data["order"] + float_barwidth * 1.5, df_data.iloc[:,-2], float_barwidth, alpha=float_opacity, color="#29A329", label='Control')
    plt.ylim(-1 , 100)
    plt.yticks(df_data["order"] + float_barwidth, df_data["variant_ID_x"])
    for idx_y in df_data["order"]:
        plt.axhline(y=idx_y + float_barwidth * 1, color="#CCCCCC", linewidth=1)
    plt.legend() 
    plt.savefig(os.path.join(str_outputFilePath, "vcf2plot.jpg"), bbox_inches='tight', dpi=100) 
Example 40
Project: CNN-CIFAR10   Author: SamKirkiles   File: main.py    MIT License 5 votes vote down vote up
def graph_results(inputs,classes,num=20):
	input_x = inputs['x']
	input_y = inputs['y']
	yhat = inputs['yhat']

	for img in range(num):
		fig = plt.figure(1)
		fig.add_subplot(121)
		plt.imshow(input_x[img,...])
		fig.add_subplot(122)
		y = yhat[img,...]
		x = [0,1,2,3,4,5,6,7,8,9]
		plt.yticks(np.arange(10), classes)
		plt.barh(x,y)
		plt.show() 
Example 41
Project: hack-lastfm   Author: CSEC-NITH   File: utils.py    MIT License 5 votes vote down vote up
def gen_graph(title,labels,frequency,filename,colour):
    x_pos=np.arange(len(labels))
    plt.figure(figsize=(25,10))
    plt.barh(x_pos, frequency, align='center', alpha=0.5, height=0.5, color=colour)
    plt.yticks(x_pos, labels)
    plt.xlabel('Playcounts')
    plt.title(title)
    plt.savefig('static/' + filename) 
Example 42
Project: CLEAR   Author: ClearExplanationsAI   File: explanation.py    MIT License 5 votes vote down vote up
def as_pyplot_figure(self, label=1, **kwargs):
        """Returns the explanation as a pyplot figure.

        Will throw an error if you don't have matplotlib installed
        Args:
            label: desired label. If you ask for a label for which an
                   explanation wasn't computed, will throw an exception.
                   Will be ignored for regression explanations.
            kwargs: keyword arguments, passed to domain_mapper

        Returns:
            pyplot figure (barchart).
        """
        import matplotlib.pyplot as plt
        exp = self.as_list(label=label, **kwargs)
        fig = plt.figure()
        vals = [x[1] for x in exp]
        names = [x[0] for x in exp]
        vals.reverse()
        names.reverse()
        colors = ['green' if x > 0 else 'red' for x in vals]
        pos = np.arange(len(exp)) + .5
        plt.barh(pos, vals, align='center', color=colors)
        plt.yticks(pos, names)
        if self.mode == "classification":
            title = 'Local explanation for class %s' % self.class_names[label]
        else:
            title = 'Local explanation'
        plt.title(title)
        return fig 
Example 43
Project: twitter-intelligence   Author: batuhaniskr   File: analysis.py    MIT License 5 votes vote down vote up
def analysis_hashtag():
    with sqlite3.connect(db_path) as db:
        conn = db
        c = conn.cursor()
        c.execute("SELECT hashtag from Tweet")
        hashtag_list = []
        for row in c.fetchall():
            if (row != ('',)):
                if " " in ''.join(row):
                    for m in ''.join(row).split(' '):
                        hashtag_list.append(m)
                else:
                    signle_item = ''.join(row)
                    hashtag_list.append(signle_item)

        counter = Counter(hashtag_list).most_common(10)
        pl.rcdefaults()

        keys = []
        performance = []

        for i in counter:
            performance.append(i[1])
            keys.append(i[0])

        pl.rcdefaults()
        y_pos = np.arange(len(keys))
        error = np.random.rand(len(keys))

        pl.barh(y_pos, performance, xerr=error, align='center', alpha=0.4, )
        pl.yticks(y_pos, keys)
        pl.xlabel('quantity')
        pl.title('hashtags')
        print(colored("[INFO] Showing graph of hashtag analysis", "green"))
        pl.show() 
Example 44
Project: ML-Pipeline-on-Financial-Distress-Data   Author: KunyuHe   File: viz.py    GNU General Public License v3.0 5 votes vote down vote up
def plot_feature_importances(importances, col_names, n=5, title=""):
    """
    Plot the feature importances of the decision tree. This credit to the
    University of Michigan.

    Inputs:
        clf: the model
        feature_names: (list) the list of strings to store feature names

    Returns:
        None
    """
    indices = np.argsort(importances)[::-1][:n]
    labels = col_names[indices][::-1]

    fig, ax = plt.subplots(figsize=[12, 8])
    plt.barh(range(n), sorted(importances, reverse=True)[:n][::-1], color='g',
             alpha=0.4, edgecolor=['black']*n)

    plt.xlabel("Feature Importance", fontproperties=AXIS)
    plt.ylabel("Feature Name", fontproperties=AXIS)
    plt.yticks(np.arange(n), labels, fontproperties=AXIS)

    figname = OUTPUT_DIR + "feature importance/" + "{}.png".format(title)
    plt.title("Feature Importance: Top {}\n".format(n) + title,
              fontproperties=AXIS)
    fig.savefig(figname, dpi=400)

    fig.tight_layout()
    plt.show(block=False)
    plt.pause(3)
    plt.close() 
Example 45
Project: actions-for-actions   Author: gsig   File: oraclesplot.py    GNU General Public License v3.0 5 votes vote down vote up
def main():
    newdata = make_data()
    setup_plot()
    allticks = []
    for i,(oracle,data) in enumerate(zip(ORACLES,newdata)):
        pos = i*(max(1,Nsub)+1)+np.array(range(max(1,Nsub)+1))
        handles = []
        for j,dat in enumerate(data):
            h = plt.barh(pos[1]+j,dat,color=COLORS[j],edgecolor=COLORS[j])
            handles.append(h)
        allticks.extend(zip([x for x in pos], ['', oracle['name'],'']))
    finalize_plot(allticks,handles)
    plt.savefig(plotname+'.pdf')
    plt.show() 
Example 46
Project: ml-analyst   Author: EpistasisLab   File: utils.py    GNU General Public License v3.0 5 votes vote down vote up
def compute_imp_score(model, model_name, training_features, training_classes, random_state):
    clf = model.named_steps[model_name]    
    # pdb.set_trace()
    if hasattr(clf, 'coef_'):
        coefs = np.abs(clf.coef_.flatten())

    else:
        coefs = getattr(clf, 'feature_importances_', None)
    if coefs is None:
        perm = PermutationImportance(
                                    estimator=model,
                                    n_iter=5,
                                    random_state=random_state,
                                    refit=False
                                    )
        perm.fit(training_features, training_classes)
        coefs = perm.feature_importances_

    
    #return (coefs-np.min(coefs))/(np.max(coefs)-np.min(coefs))
    return coefs/np.sum(coefs)

# def plot_imp_score(save_file, coefs, feature_names, seed):
#     # plot bar charts for top 10 importanct features
#     num_bar = min(10, len(coefs))
#     indices = np.argsort(coefs)[-num_bar:]
#     h=plt.figure()
#     plt.title("Feature importances")
#     plt.barh(range(num_bar), coefs[indices], color="r", align="center")
#     plt.yticks(range(num_bar), feature_names[indices])
#     plt.ylim([-1, num_bar])
#     h.tight_layout()
#     plt.savefig(save_file.split('.')[0] + '_imp_score_' + str(seed) + '.pdf')

######################################################################################### ROC Curve 
Example 47
Project: corporateZ   Author: itzmeanjan   File: utilMultiState.py    MIT License 5 votes vote down vote up
def plotAllRoCStatistics(data: Dict[str, int], targetPath: str) -> bool:
    try:
        # removing those records which didn't have any useful information regarding their RoC
        data.pop('NA', None)
        y = sorted(data, key=lambda e: data[e], reverse=True)
        y_pos = range(len(y))
        x = [data[i] for i in y]
        with plt.style.context('ggplot'):
            font = {
                'family': 'serif',
                'style': 'normal',
                'color': '#264040',
                'weight': 'regular',
                'size': 16
            }
            plt.figure(figsize=(24, 12), dpi=100)
            plt.barh(y_pos, x, align='center', color='cornflowerblue',
                     lw=1.6, joinstyle='miter')
            plt.gca().yaxis.set_ticks(y_pos)
            plt.gca().yaxis.set_ticklabels(y)
            plt.xlabel('# of Companies Registered', fontdict=font, labelpad=16)
            plt.title('Company Registration under RoC(s)',
                      fontdict=font, pad=12)
            plt.tight_layout()
            plt.savefig(targetPath, bbox_inches='tight',
                        pad_inches=.5, dpi=100, format=basename(targetPath).split('.')[-1])
            plt.close()
        return True
    except Exception:
        return False 
Example 48
Project: corporateZ   Author: itzmeanjan   File: districts.py    MIT License 5 votes vote down vote up
def plotDistributionOverDistricts(state: CountOfCompaniesUnderState, title: str, targetPath: str) -> bool:
    try:
        x = __normalizeValues__([i.count for i in state.districts])
        y = [i.name for i in state.districts]
        with plt.style.context('Solarize_Light2'):
            font = {
                'family': 'serif',
                'color': 'darkslategray',
                'weight': 'normal',
                'size': 12
            }
            plt.figure(figsize=(24, 12), dpi=100)
            # for making plots look different, I'm temporarily disabling limiting X-axis value
            # plt.xlim(0, 100)
            plt.gca().xaxis.set_major_locator(MultipleLocator(10))
            plt.gca().xaxis.set_major_formatter(PercentFormatter())
            plt.gca().xaxis.set_minor_locator(MultipleLocator(1))
            plt.gca().xaxis.set_minor_formatter(NullFormatter())
            plt.barh(y, x, align='center', color='deepskyblue', lw=1.2)
            plt.xlabel('Presence of Companies',
                       labelpad=16, fontdict=font)
            plt.title(title, fontdict=font)
            plt.tight_layout()
            plt.savefig(targetPath, bbox_inches='tight',
                        pad_inches=.4, quality=95, dpi=100)
            plt.close()
        return True
    except Exception:
        return False 
Example 49
Project: pypopgen   Author: feilchenfeldt   File: genomeplot.py    MIT License 4 votes vote down vote up
def plot_features(gene_df,annotate=True,feature_name="symbol",ax=None,xlim=None):
    if ax is None:
        ax = plt.gca()
        
    gene_df.sort('start', inplace=True)
    bar_thickness = 0.05
    text_space = 0.05
    text_dist = 0.01
    row_height = bar_thickness + text_space
    
    row = 0
    tot_rows = 0
    max_rows = 3
    prev_end = -np.inf
    for i, g in gene_df.iterrows():
        if g['start'] <= prev_end and row < max_rows:
            row += 1
        else:
            row = 0
        if annotate:
            ax.annotate(g[feature_name], ((g['start']+g['end'])/2.,-bar_thickness-row*row_height-text_dist), #
                          size=16, ha="right", va="top",rotation=30,color='k')#rotation = 270,+g['length']/2.
        plt.barh(bottom= -bar_thickness-row*row_height,
                 left=g['start'],
                 width=g['end']-g['start'],
                 height=bar_thickness,
                 color = 'yellow', alpha=1) #0.5
        tot_rows = max(tot_rows, row)
        prev_end = g['end']
        
    
           
  
    ax.set_ylim([-(tot_rows+1)*row_height,0])
    
    if xlim is None:
        ax.set_xlim([gene_df['start'].min(),gene_df['end'].max()])
    else:
        ax.set_xlim(xlim)
    ax.set_axis_off()
    
    return ax 
Example 50
Project: fanalysis   Author: OlivierGarciaDev   File: base.py    BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
def plot_row_contrib(self, num_axis, nb_values=None, figsize=None):
        """ Plot the row contributions graph
            
        For the selected axis, the graph represents the row
        contributions sorted in descending order.            
        
        Parameters
        ----------
        num_axis : int
            Select the axis for which the row contributions are plotted.
        
        nb_values : int
             Set the maximum number of values to plot.
             If nb_values is None : all the values are plotted.
        
        figsize : tuple of integers or None
            Width, height of the figure in inches.
            If not provided, defaults to rc figure.figsize
        
        Returns
        -------
        None
        """
        plt.figure(figsize=figsize)
        n_rows = len(self.row_labels_)
        n_labels = len(self.row_labels_)
        if (nb_values is not None) and (nb_values < n_labels):
            n_labels = nb_values
        limit = n_rows - n_labels
        contribs = self.row_contrib_[:, num_axis - 1]
        contribs_sorted = np.sort(contribs)[limit:n_rows]
        labels = pd.Series(self.row_labels_)[np.argsort(contribs)]\
                                                        [limit:n_rows]
        r = range(n_labels)
        bar_width = 0.5
        plt.yticks([ri + bar_width / 2 for ri in r], labels)
        plt.barh(r, contribs_sorted, height=bar_width, color="steelblue",
                 align="edge")
        plt.title("Rows contributions")
        plt.xlabel("Contributions (%)")
        plt.ylabel("Rows")
        plt.show()