本文整理汇总了Python中matplotlib.pylab.xticks方法的典型用法代码示例。如果您正苦于以下问题:Python pylab.xticks方法的具体用法?Python pylab.xticks怎么用?Python pylab.xticks使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类matplotlib.pylab
的用法示例。
在下文中一共展示了pylab.xticks方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: plot_entropy
# 需要导入模块: from matplotlib import pylab [as 别名]
# 或者: from matplotlib.pylab import xticks [as 别名]
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")
开发者ID:PacktPublishing,项目名称:Building-Machine-Learning-Systems-With-Python-Second-Edition,代码行数:23,代码来源:demo_mi.py
示例2: _plot_NWOE_bins
# 需要导入模块: from matplotlib import pylab [as 别名]
# 或者: from matplotlib.pylab import xticks [as 别名]
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
示例3: plot_pr_curve
# 需要导入模块: from matplotlib import pylab [as 别名]
# 或者: from matplotlib.pylab import xticks [as 别名]
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()
示例4: plot_word_freq_dist
# 需要导入模块: from matplotlib import pylab [as 别名]
# 或者: from matplotlib.pylab import xticks [as 别名]
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()
示例5: malt_demo
# 需要导入模块: from matplotlib import pylab [as 别名]
# 或者: from matplotlib.pylab import xticks [as 别名]
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()
示例6: _plot_correlation_func
# 需要导入模块: from matplotlib import pylab [as 别名]
# 或者: from matplotlib.pylab import xticks [as 别名]
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]])
开发者ID:PacktPublishing,项目名称:Building-Machine-Learning-Systems-With-Python-Second-Edition,代码行数:15,代码来源:demo_corr.py
示例7: plot1D_mat
# 需要导入模块: from matplotlib import pylab [as 别名]
# 或者: from matplotlib.pylab import xticks [as 别名]
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)
示例8: check_band_occupancy
# 需要导入模块: from matplotlib import pylab [as 别名]
# 或者: from matplotlib.pylab import xticks [as 别名]
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
示例9: subplot
# 需要导入模块: from matplotlib import pylab [as 别名]
# 或者: from matplotlib.pylab import xticks [as 别名]
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")
示例10: generate_box_plot
# 需要导入模块: from matplotlib import pylab [as 别名]
# 或者: from matplotlib.pylab import xticks [as 别名]
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()
示例11: generate_time_plot
# 需要导入模块: from matplotlib import pylab [as 别名]
# 或者: from matplotlib.pylab import xticks [as 别名]
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()
示例12: bar
# 需要导入模块: from matplotlib import pylab [as 别名]
# 或者: from matplotlib.pylab import xticks [as 别名]
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
示例13: plot_word_freq_dist
# 需要导入模块: from matplotlib import pylab [as 别名]
# 或者: from matplotlib.pylab import xticks [as 别名]
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()
示例14: plot_confusion_matrix
# 需要导入模块: from matplotlib import pylab [as 别名]
# 或者: from matplotlib.pylab import xticks [as 别名]
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()
示例15: plot
# 需要导入模块: from matplotlib import pylab [as 别名]
# 或者: from matplotlib.pylab import xticks [as 别名]
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()