Python matplotlib.pylab.xticks() Examples

The following are 20 code examples of matplotlib.pylab.xticks(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module matplotlib.pylab , or try the search function .
Example #1
Source File: demo_mi.py    From Building-Machine-Learning-Systems-With-Python-Second-Edition with MIT License 6 votes vote down vote up
def plot_entropy():
    pylab.clf()
    pylab.figure(num=None, figsize=(5, 4))

    title = "Entropy $H(X)$"
    pylab.title(title)
    pylab.xlabel("$P(X=$coin will show heads up$)$")
    pylab.ylabel("$H(X)$")

    pylab.xlim(xmin=0, xmax=1.1)
    x = np.arange(0.001, 1, 0.001)
    y = -x * np.log2(x) - (1 - x) * np.log2(1 - x)
    pylab.plot(x, y)
    # pylab.xticks([w*7*24 for w in [0,1,2,3,4]], ['week %i'%(w+1) for w in
    # [0,1,2,3,4]])

    pylab.autoscale(tight=True)
    pylab.grid(True)

    filename = "entropy_demo.png"
    pylab.savefig(os.path.join(CHART_DIR, filename), bbox_inches="tight") 
Example #2
Source File: utils.py    From ndvr-dml with Apache License 2.0 6 votes vote down vote up
def plot_pr_curve(pr_curve_dml, pr_curve_base, title):
    """
      Function that plots the PR-curve.

      Args:
        pr_curve: the values of precision for each recall value
        title: the title of the plot
    """
    plt.figure(figsize=(16, 9))
    plt.plot(np.arange(0.0, 1.05, 0.05),
             pr_curve_base, color='r', marker='o', linewidth=3, markersize=10)
    plt.plot(np.arange(0.0, 1.05, 0.05),
             pr_curve_dml, color='b', marker='o', linewidth=3, markersize=10)
    plt.grid(True, linestyle='dotted')
    plt.xlabel('Recall', color='k', fontsize=27)
    plt.ylabel('Precision', color='k', fontsize=27)
    plt.yticks(color='k', fontsize=20)
    plt.xticks(color='k', fontsize=20)
    plt.ylim([0.0, 1.05])
    plt.xlim([0.0, 1.0])
    plt.title(title, color='k', fontsize=27)
    plt.tight_layout()
    plt.show() 
Example #3
Source File: base.py    From pylift with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def _plot_NWOE_bins(NWOE_dict, feats):
    """
    Plots the NWOE by bin for the subset of features interested in (form of list)

    Parameters
    ----------
    - NWOE_dict = dictionary output of `NWOE` function
    - feats = list of features to plot NWOE for

    Returns
    -------
    - plots of NWOE for each feature by bin
    """

    for feat in feats:
        fig, ax = _plot_defaults()
        feat_df = NWOE_dict[feat].reset_index()
        plt.bar(range(len(feat_df)), feat_df['NWOE'], tick_label=feat_df[str(feat)+'_bin'], color='k', alpha=0.5)
        plt.xticks(rotation='vertical')
        ax.set_title('NWOE by bin for '+str(feat))
        ax.set_xlabel('Bin Interval');
    return ax 
Example #4
Source File: base.py    From pylift with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def _plot_NWOE_bins(NWOE_dict, feats):
    """
    Plots the NWOE by bin for the subset of features interested in (form of list)

    Parameters
    ----------
    - NWOE_dict = dictionary output of `NWOE` function
    - feats = list of features to plot NWOE for

    Returns
    -------
    - plots of NWOE for each feature by bin
    """

    for feat in feats:
        fig, ax = _plot_defaults()
        feat_df = NWOE_dict[feat].reset_index()
        plt.bar(range(len(feat_df)), feat_df['NWOE'], tick_label=feat_df[str(feat)+'_bin'], color='k', alpha=0.5)
        plt.xticks(rotation='vertical')
        ax.set_title('NWOE by bin for '+str(feat))
        ax.set_xlabel('Bin Interval');
    return ax 
Example #5
Source File: evaluation.py    From deepecg with MIT License 5 votes vote down vote up
def plot_confusion_matrix(y_true, y_pred, classes, figure_size=(8, 8)):
    """This function plots a confusion matrix."""
    # Compute confusion matrix
    cm = confusion_matrix(y_true, y_pred)
    cm = cm.astype('float') / cm.sum(axis=1)[:, np.newaxis] * 100

    # Build Laussen Labs colormap
    cmap = LinearSegmentedColormap.from_list('laussen_labs_green', ['w', '#43BB9B'], N=256)

    # Setup plot
    plt.figure(figsize=figure_size)

    # Plot confusion matrix
    plt.imshow(cm, interpolation='nearest', cmap=cmap)

    # Modify axes
    tick_marks = np.arange(len(classes))
    plt.xticks(tick_marks, classes, rotation=90)
    plt.yticks(tick_marks, classes)
    thresh = cm.max() / 1.5
    for i, j in itertools.product(range(cm.shape[0]), range(cm.shape[1])):
        plt.text(j, i, str(np.round(cm[i, j], 2)) + ' %', horizontalalignment="center",
                 color="white" if cm[i, j] > thresh else "black", fontsize=20)
    plt.xticks(fontsize=16)
    plt.yticks(fontsize=16)
    plt.tight_layout()
    plt.ylabel('True Label', fontsize=25)
    plt.xlabel('Predicted Label', fontsize=25)

    plt.show() 
Example #6
Source File: wordfreq_app.py    From V1EngineeringInc-Docs with Creative Commons Attribution Share Alike 4.0 International 5 votes vote down vote up
def plot_word_freq_dist(text):
    fd = text.vocab()

    samples = [item for item, _ in fd.most_common(50)]
    values = [fd[sample] for sample in samples]
    values = [sum(values[: i + 1]) * 100.0 / fd.N() for i in range(len(values))]
    pylab.title(text.name)
    pylab.xlabel("Samples")
    pylab.ylabel("Cumulative Percentage")
    pylab.plot(values)
    pylab.xticks(range(len(samples)), [str(s) for s in samples], rotation=90)
    pylab.show() 
Example #7
Source File: run.py    From ipython-cypher with GNU General Public License v2.0 5 votes vote down vote up
def bar(self, key_word_sep=" ", title=None, **kwargs):
        """Generates a pylab bar plot from the result set.

        ``matplotlib`` must be installed, and in an
        IPython Notebook, inlining must be on::

            %%matplotlib inline

        The last quantitative column is taken as the Y values;
        all other columns are combined to label the X axis.

        :param title: plot title, defaults to names of Y value columns
        :param key_word_sep: string used to separate column values
                             from each other in labels

        Any additional keyword arguments will be passsed
        through to ``matplotlib.pylab.bar``.
        """
        if not plt:
            raise ImportError("Try installing matplotlib first.")
        self.guess_pie_columns(xlabel_sep=key_word_sep)
        plot = plt.bar(range(len(self.ys[0])), self.ys[0], **kwargs)
        if self.xlabels:
            plt.xticks(range(len(self.xlabels)), self.xlabels,
                       rotation=45)
        plt.xlabel(self.xlabel)
        plt.ylabel(self.ys[0].name)
        return plot 
Example #8
Source File: generate_plots.py    From hand_eye_calibration with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def generate_time_plot(methods, datasets, runtimes_per_method, colors):
  num_methods = len(methods)
  num_datasets = len(datasets)
  x_ticks = np.linspace(0., 1., num_methods)

  width = 0.6 / num_methods / num_datasets
  spacing = 0.4 / num_methods / num_datasets
  fig, ax1 = plt.subplots()
  ax1.set_ylabel('Time [s]', color='b')
  ax1.tick_params('y', colors='b')
  ax1.set_yscale('log')
  fig.suptitle("Hand-Eye Calibration Method Timings", fontsize='24')
  handles = []
  for i, dataset in enumerate(datasets):
    runtimes = [runtimes_per_method[dataset][method] for method in methods]
    bp = ax1.boxplot(
        runtimes, 0, '',
        positions=(x_ticks + (i - num_datasets / 2. + 0.5) *
                   spacing * 2),
        widths=width)
    plt.setp(bp['boxes'], color=colors[i], linewidth=line_width)
    plt.setp(bp['whiskers'], color=colors[i], linewidth=line_width)
    plt.setp(bp['fliers'], color=colors[i],
             marker='+', linewidth=line_width)
    plt.setp(bp['medians'], color=colors[i],
             marker='+', linewidth=line_width)
    plt.setp(bp['caps'], color=colors[i], linewidth=line_width)
    handles.append(mpatches.Patch(color=colors[i], label=dataset))
  plt.legend(handles=handles, loc=2)

  plt.xticks(x_ticks, methods)
  plt.xlim(x_ticks[0] - 2.5 * spacing * num_datasets,
           x_ticks[-1] + 2.5 * spacing * num_datasets)

  plt.show() 
Example #9
Source File: generate_plots.py    From hand_eye_calibration with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def generate_box_plot(dataset, methods, position_rmses, orientation_rmses):

  num_methods = len(methods)
  x_ticks = np.linspace(0., 1., num_methods)

  width = 0.3 / num_methods
  spacing = 0.3 / num_methods
  fig, ax1 = plt.subplots()
  ax1.set_ylabel('RMSE position [m]', color='b')
  ax1.tick_params('y', colors='b')
  fig.suptitle(
      "Hand-Eye Calibration Method Error {}".format(dataset), fontsize='24')
  bp_position = ax1.boxplot(position_rmses, 0, '',
                            positions=x_ticks - spacing, widths=width)
  plt.setp(bp_position['boxes'], color='blue', linewidth=line_width)
  plt.setp(bp_position['whiskers'], color='blue', linewidth=line_width)
  plt.setp(bp_position['fliers'], color='blue',
           marker='+', linewidth=line_width)
  plt.setp(bp_position['caps'], color='blue', linewidth=line_width)
  plt.setp(bp_position['medians'], color='blue', linewidth=line_width)
  ax2 = ax1.twinx()
  ax2.set_ylabel('RMSE Orientation [$^\circ$]', color='g')
  ax2.tick_params('y', colors='g')
  bp_orientation = ax2.boxplot(
      orientation_rmses, 0, '', positions=x_ticks + spacing, widths=width)
  plt.setp(bp_orientation['boxes'], color='green', linewidth=line_width)
  plt.setp(bp_orientation['whiskers'], color='green', linewidth=line_width)
  plt.setp(bp_orientation['fliers'], color='green',
           marker='+')
  plt.setp(bp_orientation['caps'], color='green', linewidth=line_width)
  plt.setp(bp_orientation['medians'], color='green', linewidth=line_width)

  plt.xticks(x_ticks, methods)
  plt.xlim(x_ticks[0] - 2.5 * spacing, x_ticks[-1] + 2.5 * spacing)

  plt.show() 
Example #10
Source File: dds_parallel_plot.py    From spotpy with MIT License 5 votes vote down vote up
def subplot(data, name, ylabel):
    fig = plt.figure(figsize=(20, 6))
    ax = plt.subplot(111)
    rep_labels = [str(j) for j in reps]
    x_pos = [i for i, _ in enumerate(rep_labels)]
    X = np.arange(len(data))
    ax_plot = ax.bar(x_pos, data, color=color_map(data_normalizer(data)), width=0.45)

    plt.xticks(x_pos, rep_labels)
    plt.xlabel("Repetitions")
    plt.ylabel(ylabel)

    autolabel(ax, ax_plot)
    plt.savefig(name + ".png") 
Example #11
Source File: interactive.py    From pyiron with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def check_band_occupancy(self, plot=True):
        """
            Check whether there are still empty bands available.

            args:
                plot (bool): plots occupancy of the last step

            returns:
                True if there are still empty bands
        """
        import matplotlib.pylab as plt
        elec_dict = self._job['output/generic/dft']['n_valence']
        if elec_dict is None:
            raise AssertionError('Number of electrons not parsed')
        n_elec = np.sum([elec_dict[k]
                         for k in self._job.structure.get_chemical_symbols()])
        n_elec = int(np.ceil(n_elec/2))
        bands = self._job['output/generic/dft/bands_occ'][-1]
        bands = bands.reshape(-1, bands.shape[-1])
        max_occ = np.sum(bands>0, axis=-1).max()
        n_bands = bands.shape[-1]
        if plot:
            xticks = np.arange(1, n_bands+1)
            plt.xlabel('Electron number')
            plt.ylabel('Occupancy')
            if n_bands<20:
                plt.xticks(xticks)
            plt.axvline(n_elec, label='#electrons: {}'.format(n_elec))
            plt.axvline(max_occ, color='red',
                label='Max occupancy: {}'.format(max_occ))
            plt.axvline(n_bands, color='green',
                label='Number of bands: {}'.format(n_bands))
            plt.plot(xticks, bands.T, 'x', color='black')
            plt.legend()
        if max_occ < n_bands:
            return True
        else:
            return False 
Example #12
Source File: plot.py    From POT with MIT License 5 votes vote down vote up
def plot1D_mat(a, b, M, title=''):
    """ Plot matrix M  with the source and target 1D distribution

    Creates a subplot with the source distribution a on the left and
    target distribution b on the tot. The matrix M is shown in between.


    Parameters
    ----------
    a : ndarray, shape (na,)
        Source distribution
    b : ndarray, shape (nb,)
        Target distribution
    M : ndarray, shape (na, nb)
        Matrix to plot
    """
    na, nb = M.shape

    gs = gridspec.GridSpec(3, 3)

    xa = np.arange(na)
    xb = np.arange(nb)

    ax1 = pl.subplot(gs[0, 1:])
    pl.plot(xb, b, 'r', label='Target distribution')
    pl.yticks(())
    pl.title(title)

    ax2 = pl.subplot(gs[1:, 0])
    pl.plot(a, xa, 'b', label='Source distribution')
    pl.gca().invert_xaxis()
    pl.gca().invert_yaxis()
    pl.xticks(())

    pl.subplot(gs[1:, 1:], sharex=ax1, sharey=ax2)
    pl.imshow(M, interpolation='nearest')
    pl.axis('off')

    pl.xlim((0, nb))
    pl.tight_layout()
    pl.subplots_adjust(wspace=0., hspace=0.2) 
Example #13
Source File: demo_corr.py    From Building-Machine-Learning-Systems-With-Python-Second-Edition with MIT License 5 votes vote down vote up
def _plot_correlation_func(x, y):

    r, p = pearsonr(x, y)
    title = "Cor($X_1$, $X_2$) = %.3f" % r
    pylab.scatter(x, y)
    pylab.title(title)
    pylab.xlabel("$X_1$")
    pylab.ylabel("$X_2$")

    f1 = scipy.poly1d(scipy.polyfit(x, y, 1))
    pylab.plot(x, f1(x), "r--", linewidth=2)
    # pylab.xticks([w*7*24 for w in [0,1,2,3,4]], ['week %i'%(w+1) for w in
    # [0,1,2,3,4]]) 
Example #14
Source File: dependencygraph.py    From razzy-spinner with GNU General Public License v3.0 5 votes vote down vote up
def malt_demo(nx=False):
    """
    A demonstration of the result of reading a dependency
    version of the first sentence of the Penn Treebank.
    """
    dg = DependencyGraph("""Pierre  NNP     2       NMOD
Vinken  NNP     8       SUB
,       ,       2       P
61      CD      5       NMOD
years   NNS     6       AMOD
old     JJ      2       NMOD
,       ,       2       P
will    MD      0       ROOT
join    VB      8       VC
the     DT      11      NMOD
board   NN      9       OBJ
as      IN      9       VMOD
a       DT      15      NMOD
nonexecutive    JJ      15      NMOD
director        NN      12      PMOD
Nov.    NNP     9       VMOD
29      CD      16      NMOD
.       .       9       VMOD
""")
    tree = dg.tree()
    tree.pprint()
    if nx:
        # currently doesn't work
        import networkx
        from matplotlib import pylab

        g = dg.nx_graph()
        g.info()
        pos = networkx.spring_layout(g, dim=1)
        networkx.draw_networkx_nodes(g, pos, node_size=50)
        # networkx.draw_networkx_edges(g, pos, edge_color='k', width=8)
        networkx.draw_networkx_labels(g, pos, dg.nx_labels)
        pylab.xticks([])
        pylab.yticks([])
        pylab.savefig('tree.png')
        pylab.show() 
Example #15
Source File: wordfreq_app.py    From razzy-spinner with GNU General Public License v3.0 5 votes vote down vote up
def plot_word_freq_dist(text):
    fd = text.vocab()

    samples = [item for item, _ in fd.most_common(50)]
    values = [fd[sample] for sample in samples]
    values = [sum(values[:i+1]) * 100.0/fd.N() for i in range(len(values))]
    pylab.title(text.name)
    pylab.xlabel("Samples")
    pylab.ylabel("Cumulative Percentage")
    pylab.plot(values)
    pylab.xticks(range(len(samples)), [str(s) for s in samples], rotation=90)
    pylab.show() 
Example #16
Source File: utils.py    From miosqp with Apache License 2.0 4 votes vote down vote up
def plot(results, time):
    """
    Plot simulation results
    """

    t = time.t
    t_init = t[0] + time.init_periods * time.Nstpp * time.Ts
    t_end = t_init + time.Nstpp * time.Ts
    Y_phase = results.Y_phase
    Y_star_phase = results.Y_star_phase
    U = results.U

    x_ticks = np.arange(t_init, t_end + 1e-08, 0.0025)
    x_ticks_labels = ['0', '', '5', '', '10', '', '15', '', '20']


    # Plot currents
    plt.figure()
    plt.plot(t[:-1], Y_phase[0,:], '-', color=colors['o'])
    plt.plot(t[:-1], Y_star_phase[0,:], '--', color=colors['o'])
    plt.plot(t[:-1], Y_phase[1,:], '-', color=colors['g'])
    plt.plot(t[:-1], Y_star_phase[1,:], '--', color=colors['g'])
    plt.plot(t[:-1], Y_phase[2,:], '-', color=colors['b'])
    plt.plot(t[:-1], Y_star_phase[2,:], '--', color=colors['b'])
    axes = plt.gca()
    axes.set_xlim([t_init, t_end])
    axes.set_ylim([-1.25, 1.25])
    plt.xticks(x_ticks, x_ticks_labels)
    plt.grid()
    axes.set_xlabel('Time [ms]')
    plt.tight_layout()
    plt.savefig('results/power_converter_currents.pdf')
    plt.show(block=False)


    # Plot inputs
    fig, ax = plt.subplots(3, 1)
    ax[0].step(t[:-1], U[0, :], color=colors['o'])
    ax[0].set_xlim([t_init, t_end])
    ax[0].set_ylim([-1.25, 1.25])
    ax[0].grid(True)
    ax[0].set_xticks(x_ticks)
    ax[0].set_xticklabels(x_ticks_labels)
    ax[1].step(t[:-1], U[1, :], color=colors['g'])
    ax[1].set_ylim([-1.25, 1.25])
    ax[1].set_xlim([t_init, t_end])
    ax[1].set_xticks(x_ticks)
    ax[1].set_xticklabels(x_ticks_labels)
    ax[1].grid(True)
    ax[2].step(t[:-1], U[2, :], color=colors['b'])
    ax[2].set_ylim([-1.25, 1.25])
    ax[2].set_xlim([t_init, t_end])
    ax[2].set_xlabel('Time [ms]')
    ax[2].grid(True)
    ax[2].set_xticks(x_ticks)
    ax[2].set_xticklabels(x_ticks_labels)
    plt.tight_layout()
    plt.savefig('results/power_converter_inputs.pdf')
    plt.show(block=False) 
Example #17
Source File: GaussViz.py    From refinery with MIT License 4 votes vote down vote up
def plotCovMatFromHModel(hmodel, compListToPlot=None, compsToHighlight=None, wTHR=0.001):
  ''' Plot cov matrix visualization for each "significant" component in hmodel
      Args
      -------
      hmodel : bnpy HModel object
      compListToPlot : array-like of integer IDs of components within hmodel
      compsToHighlight : int or array-like of integer IDs to highlight
                          if None, all components get unique colors
                          if not None, only highlighted components get colors.
      wTHR : float threshold on minimum weight assigned to comp tobe "plottable"      
  '''
  if compsToHighlight is not None:
    compsToHighlight = np.asarray(compsToHighlight)
    if compsToHighlight.ndim == 0:
      compsToHighlight = np.asarray([compsToHighlight])
  else:
    compsToHighlight = list()  
  if compListToPlot is None:
    compListToPlot = np.arange(0, hmodel.allocModel.K)
  try:
    w = np.exp(hmodel.allocModel.Elogw)
  except Exception:
    w = hmodel.allocModel.w

  nRow = 2
  nCol = np.ceil(hmodel.obsModel.K/2.0)

  colorID = 0
  for plotID, kk in enumerate(compListToPlot):
    if w[kk] < wTHR and kk not in compsToHighlight:
      Sigma = getEmptyCompSigmaImage(hmodel.obsModel.D)
      clim = [0, 1]
    else:
      Sigma = hmodel.obsModel.get_covar_mat_for_comp(kk)
      clim = [-.25, 1]
    pylab.subplot(nRow, nCol, plotID)
    pylab.imshow(Sigma, interpolation='nearest', cmap='hot', clim=clim)
    pylab.xticks([])
    pylab.yticks([])
    pylab.xlabel('%.2f' % (w[kk]))
    if kk in compsToHighlight:
      pylab.xlabel('***') 
Example #18
Source File: probability.py    From razzy-spinner with GNU General Public License v3.0 4 votes vote down vote up
def plot(self, *args, **kwargs):
        """
        Plot the given samples from the conditional frequency distribution.
        For a cumulative plot, specify cumulative=True.
        (Requires Matplotlib to be installed.)

        :param samples: The samples to plot
        :type samples: list
        :param title: The title for the graph
        :type title: str
        :param conditions: The conditions to plot (default is all)
        :type conditions: list
        """
        try:
            from matplotlib import pylab
        except ImportError:
            raise ValueError('The plot function requires matplotlib to be installed.'
                         'See http://matplotlib.org/')

        cumulative = _get_kwarg(kwargs, 'cumulative', False)
        conditions = _get_kwarg(kwargs, 'conditions', sorted(self.conditions()))
        title = _get_kwarg(kwargs, 'title', '')
        samples = _get_kwarg(kwargs, 'samples',
                             sorted(set(v for c in conditions for v in self[c])))  # this computation could be wasted
        if not "linewidth" in kwargs:
            kwargs["linewidth"] = 2

        for condition in conditions:
            if cumulative:
                freqs = list(self[condition]._cumulative_frequencies(samples))
                ylabel = "Cumulative Counts"
                legend_loc = 'lower right'
            else:
                freqs = [self[condition][sample] for sample in samples]
                ylabel = "Counts"
                legend_loc = 'upper right'
            # percents = [f * 100 for f in freqs] only in ConditionalProbDist?
            kwargs['label'] = "%s" % condition
            pylab.plot(freqs, *args, **kwargs)

        pylab.legend(loc=legend_loc)
        pylab.grid(True, color="silver")
        pylab.xticks(range(len(samples)), [compat.text_type(s) for s in samples], rotation=90)
        if title:
            pylab.title(title)
        pylab.xlabel("Samples")
        pylab.ylabel(ylabel)
        pylab.show() 
Example #19
Source File: dependencygraph.py    From V1EngineeringInc-Docs with Creative Commons Attribution Share Alike 4.0 International 4 votes vote down vote up
def malt_demo(nx=False):
    """
    A demonstration of the result of reading a dependency
    version of the first sentence of the Penn Treebank.
    """
    dg = DependencyGraph(
        """Pierre  NNP     2       NMOD
Vinken  NNP     8       SUB
,       ,       2       P
61      CD      5       NMOD
years   NNS     6       AMOD
old     JJ      2       NMOD
,       ,       2       P
will    MD      0       ROOT
join    VB      8       VC
the     DT      11      NMOD
board   NN      9       OBJ
as      IN      9       VMOD
a       DT      15      NMOD
nonexecutive    JJ      15      NMOD
director        NN      12      PMOD
Nov.    NNP     9       VMOD
29      CD      16      NMOD
.       .       9       VMOD
"""
    )
    tree = dg.tree()
    tree.pprint()
    if nx:
        # currently doesn't work
        import networkx
        from matplotlib import pylab

        g = dg.nx_graph()
        g.info()
        pos = networkx.spring_layout(g, dim=1)
        networkx.draw_networkx_nodes(g, pos, node_size=50)
        # networkx.draw_networkx_edges(g, pos, edge_color='k', width=8)
        networkx.draw_networkx_labels(g, pos, dg.nx_labels)
        pylab.xticks([])
        pylab.yticks([])
        pylab.savefig('tree.png')
        pylab.show() 
Example #20
Source File: probability.py    From razzy-spinner with GNU General Public License v3.0 4 votes vote down vote up
def plot(self, *args, **kwargs):
        """
        Plot samples from the frequency distribution
        displaying the most frequent sample first.  If an integer
        parameter is supplied, stop after this many samples have been
        plotted.  For a cumulative plot, specify cumulative=True.
        (Requires Matplotlib to be installed.)

        :param title: The title for the graph
        :type title: str
        :param cumulative: A flag to specify whether the plot is cumulative (default = False)
        :type title: bool
        """
        try:
            from matplotlib import pylab
        except ImportError:
            raise ValueError('The plot function requires matplotlib to be installed.'
                         'See http://matplotlib.org/')

        if len(args) == 0:
            args = [len(self)]
        samples = [item for item, _ in self.most_common(*args)]

        cumulative = _get_kwarg(kwargs, 'cumulative', False)
        if cumulative:
            freqs = list(self._cumulative_frequencies(samples))
            ylabel = "Cumulative Counts"
        else:
            freqs = [self[sample] for sample in samples]
            ylabel = "Counts"
        # percents = [f * 100 for f in freqs]  only in ProbDist?

        pylab.grid(True, color="silver")
        if not "linewidth" in kwargs:
            kwargs["linewidth"] = 2
        if "title" in kwargs:
            pylab.title(kwargs["title"])
            del kwargs["title"]
        pylab.plot(freqs, **kwargs)
        pylab.xticks(range(len(samples)), [compat.text_type(s) for s in samples], rotation=90)
        pylab.xlabel("Samples")
        pylab.ylabel(ylabel)
        pylab.show()