本文整理汇总了Python中matplotlib.pyplot.xticks函数的典型用法代码示例。如果您正苦于以下问题:Python xticks函数的具体用法?Python xticks怎么用?Python xticks使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了xticks函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: test_rotated_labels_parameters
def test_rotated_labels_parameters(x_alignment, y_alignment,
x_tick_label_width, y_tick_label_width,
rotation):
fig, _ = __plot()
if x_alignment:
plt.xticks(ha=x_alignment, rotation=rotation)
if y_alignment:
plt.yticks(ha=y_alignment, rotation=rotation)
# convert to tikz file
_, tmp_base = tempfile.mkstemp()
tikz_file = tmp_base + '_tikz.tex'
extra_dict = {}
if x_tick_label_width:
extra_dict['x tick label text width'] = x_tick_label_width
if y_tick_label_width:
extra_dict['y tick label text width'] = y_tick_label_width
matplotlib2tikz.save(
tikz_file,
figurewidth='7.5cm',
extra_axis_parameters=extra_dict
)
# close figure
plt.close(fig)
# delete file
os.unlink(tikz_file)
示例2: plot_scenario
def plot_scenario(strategies, names, scenario_id=1):
probabilities = get_scenario(scenario_id)
plt.figure(figsize=(6, 4.5))
ax = plt.subplot(111)
ax.spines["top"].set_visible(False)
ax.spines["bottom"].set_visible(False)
ax.spines["right"].set_visible(False)
ax.spines["left"].set_visible(False)
ax.get_xaxis().tick_bottom()
ax.get_yaxis().tick_left()
plt.yticks(fontsize=14)
plt.xticks(fontsize=14)
plt.xlim((0, 1300))
# Remove the tick marks; they are unnecessary with the tick lines we just plotted.
plt.tick_params(axis="both", which="both", bottom="on", top="off",
labelbottom="on", left="off", right="off", labelleft="on")
for rank, (strategy, name) in enumerate(zip(strategies, names)):
plot_strategy(probabilities, strategy, name, rank)
plt.title("Bandits: " + str(probabilities), fontweight='bold')
plt.xlabel('Number of Trials', fontsize=14)
plt.ylabel('Cumulative Regret', fontsize=14)
plt.legend(names)
plt.show()
示例3: showOverlapTable
def showOverlapTable(modes_x, modes_y, **kwargs):
"""Show overlap table using :func:`~matplotlib.pyplot.pcolor`. *modes_x*
and *modes_y* are sets of normal modes, and correspond to x and y axes of
the plot. Note that mode indices are incremented by 1. List of modes
is assumed to contain a set of contiguous modes from the same model.
Default arguments for :func:`~matplotlib.pyplot.pcolor`:
* ``cmap=plt.cm.jet``
* ``norm=plt.normalize(0, 1)``"""
import matplotlib.pyplot as plt
overlap = abs(calcOverlap(modes_y, modes_x))
if overlap.ndim == 0:
overlap = np.array([[overlap]])
elif overlap.ndim == 1:
overlap = overlap.reshape((modes_y.numModes(), modes_x.numModes()))
cmap = kwargs.pop('cmap', plt.cm.jet)
norm = kwargs.pop('norm', plt.normalize(0, 1))
show = (plt.pcolor(overlap, cmap=cmap, norm=norm, **kwargs),
plt.colorbar())
x_range = np.arange(1, modes_x.numModes() + 1)
plt.xticks(x_range-0.5, x_range)
plt.xlabel(str(modes_x))
y_range = np.arange(1, modes_y.numModes() + 1)
plt.yticks(y_range-0.5, y_range)
plt.ylabel(str(modes_y))
plt.axis([0, modes_x.numModes(), 0, modes_y.numModes()])
if SETTINGS['auto_show']:
showFigure()
return show
示例4: make_bar
def make_bar(
x,
y,
f_name,
title=None,
legend=None,
x_label=None,
y_label=None,
x_ticks=None,
y_ticks=None,
):
fig = plt.figure()
if title is not None:
plt.title(title, fontsize=16)
if x_label is not None:
plt.ylabel(x_label)
if y_label is not None:
plt.xlabel(y_label)
if x_ticks is not None:
plt.xticks(x, x_ticks)
if y_ticks is not None:
plt.yticks(y_ticks)
plt.bar(x, y, align="center")
if legend is not None:
plt.legend(legend)
plt.savefig(f_name)
plt.close(fig)
示例5: tuning
def tuning(x, y, err=None, smooth=None, ylabel=None, pal=None):
"""
Plot a tuning curve
"""
if smooth is not None:
xs, ys = smoothfit(x, y, smooth)
plt.plot(xs, ys, linewidth=4, color="black", zorder=1)
else:
ys = asarray([0])
if pal is None:
pal = sns.color_palette("husl", n_colors=len(x) + 6)
pal = pal[2 : 2 + len(x)][::-1]
plt.scatter(x, y, s=300, linewidth=0, color=pal, zorder=2)
if err is not None:
plt.errorbar(x, y, yerr=err, linestyle="None", ecolor="black", zorder=1)
plt.xlabel("Wall distance (mm)")
plt.ylabel(ylabel)
plt.xlim([-2.5, 32.5])
errTmp = err
errTmp[isnan(err)] = 0
rng = max([nanmax(ys), nanmax(y + errTmp)])
plt.ylim([0 - rng * 0.1, rng + rng * 0.1])
plt.yticks(linspace(0, rng, 3))
plt.xticks(range(0, 40, 10))
sns.despine()
return rng
示例6: disc_norm
def disc_norm():
x = np.linspace(-3,3,100)
y = st.norm.pdf(x,0,1)
fig, ax = plt.subplots()
fig.canvas.draw()
ax.plot(x,y)
fill1_x = np.linspace(-2,-1.5,100)
fill1_y = st.norm.pdf(fill1_x,0,1)
fill2_x = np.linspace(-1.5,-1,100)
fill2_y = st.norm.pdf(fill2_x,0,1)
ax.fill_between(fill1_x,0,fill1_y,facecolor = 'blue', edgecolor = 'k',alpha = 0.75)
ax.fill_between(fill2_x,0,fill2_y,facecolor = 'blue', edgecolor = 'k',alpha = 0.75)
for label in ax.get_yticklabels():
label.set_visible(False)
for tick in ax.get_xticklines():
tick.set_visible(False)
for tick in ax.get_yticklines():
tick.set_visible(False)
plt.rc("font", size = 16)
plt.xticks([-2,-1.5,-1])
labels = [item.get_text() for item in ax.get_xticklabels()]
labels[0] = r"$v_k$"
labels[1] = r"$\varepsilon_k$"
labels[2] = r"$v_{k+1}$"
ax.set_xticklabels(labels)
plt.ylim([0, .45])
plt.savefig('discnorm.pdf')
plt.clf()
示例7: plot_jacobian
def plot_jacobian(A, name, cmap= plt.cm.coolwarm, normalize=True, precision=1e-6):
"""
Customized visualization of jacobian matrices for observing
sparsity patterns
"""
plt.figure()
fig, ax = plt.subplots()
if normalize is True:
plt.imshow(A, interpolation='none', cmap=cmap,
norm = mpl.colors.Normalize(vmin=-1.,vmax=1.))
else:
plt.imshow(A, interpolation='none', cmap=cmap)
plt.colorbar(format=ticker.FuncFormatter(fmt))
ax.spy(A, marker='.', markersize=0, precision=precision)
ax.spines['right'].set_visible(True)
ax.spines['bottom'].set_visible(True)
ax.xaxis.set_ticks_position('top')
ax.yaxis.set_ticks_position('left')
xlabels = np.linspace(0, A.shape[0], 5, True, dtype=int)
ylabels = np.linspace(0, A.shape[1], 5, True, dtype=int)
plt.xticks(xlabels)
plt.yticks(ylabels)
plt.savefig(name, bbox_inches='tight', pad_inches=0.05)
plt.close()
return
示例8: plot_top_candidates
def plot_top_candidates(tweets, n, gop, save_to = None):
'''
Plots the counts of top n candidate pair mentions given a Tweets class.
Note: used for task 2.
'''
counts = tweets.top_pairs(n, gop)
pairs = []
mentions = []
for pair, ment in counts:
p = pair.split("|")
c0 = CANDIDATE_NAMES[ p[0] ]
c1 = CANDIDATE_NAMES[ p[1] ]
pairs.append(c0 + "\n" + c1)
mentions.append(ment)
fig = plt.figure(figsize = (FIGWIDTH, FIGHEIGHT))
plt.bar(range(len(counts)), mentions)
plt.xticks(range(len(counts)), pairs, rotation = 'vertical')
if gop:
plt.title("Pairs of GOP Candidates Mentioned most Frequently together")
else:
plt.title("Pairs of Candidates Mentioned most Frequently together")
plt.xlabel("Number of Mentions")
plt.ylabel("Number of Tweets")
plt.show()
if save_to:
fig.savefig(save_to)
示例9: plot_per_min_debate
def plot_per_min_debate(tweets, cands, interval, \
start = DEBATE_START // 60, end = DEBATE_END // 60, tic_inc = 15, save_to = None):
'''
Plots data from beg of debate to end. For Task 4a.
Note: start and end should be in minutes, not seconds
'''
fig = plt.figure(figsize = (FIGWIDTH, FIGHEIGHT))
period = range(start, end, interval)
c_dict = tweets.get_candidate_mentions_per_minute(cands, interval, period)
y = np.row_stack()
for candidate in c_dict:
plt.plot(period, c_dict[candidate], label = CANDIDATE_NAMES[candidate])
if interval == 1:
plt.title("Mentions per Minute During Debate")
else:
plt.title("Mentions per {} minutes before, during, and after debate".\
format(interval))
plt.xlabel("Time")
plt.ylabel("Number of Tweets")
plt.legend()
ticks_range = range(start, end, tic_inc)
labels = list(map(lambda x: str(x - start) + " min", ticks_range))
plt.xticks(ticks_range, labels, rotation = 'vertical')
plt.xlim( (start, end) )
if save_to:
fig.savefig(save_to)
plt.show()
示例10: barPlot
def barPlot(self, datalist, threshold, figname):
tally = self.geneCount(datalist)
#Limit the items plotted to those over 1% of the read mass
geneplot = defaultdict()
for g, n in tally.iteritems():
if n > int(sum(tally.values())*threshold):
geneplot[g] = n
#Get plotting values
olist = OrderedDict(sorted(geneplot.items(),key=lambda t: t[0]))
summe = sum(olist.values())
freq = [float(x)/float(summe) for x in olist.values()]
#Create plot
fig = plt.figure()
width = .35
ind = np.arange(len(geneplot.keys()))
plt.bar(ind, freq)
plt.xticks(ind + width, geneplot.keys())
locs, labels = plt.xticks()
plt.setp(labels, rotation=90)
plt.show()
fig.savefig(figname)
print("Saved bar plot as: "+figname)
示例11: graph_by_sender
def graph_by_sender(self):
mac_adresses = {} # new dictionary
for pkt in self.pcap_file:
mac_adresses.update({pkt[Dot11].addr2: 0})
for pkt in self.pcap_file:
mac_adresses[pkt[Dot11].addr2] += 1
MA = []
for ma in mac_adresses:
MA.append(mac_adresses[ma])
plt.clf()
plt.suptitle('Number of packets of every sender', fontsize=14, fontweight='bold')
plt.bar(range(len(mac_adresses)), sorted(MA), align='center', color=MY_COLORS)
plt.xticks(range(len(mac_adresses)), sorted(mac_adresses.keys()))
plt.rcParams.update({'font.size': 10})
plt.xlabel('Senders mac addresses')
plt.ylabel('Number of packets')
# Set tick colors:
ax = plt.gca()
ax.tick_params(axis='x', colors='k')
ax.tick_params(axis='y', colors='r')
ax.set_xticklabels(ax.xaxis.get_majorticklabels(), rotation=45)
plt.show()
示例12: template_matching
def template_matching():
img = cv2.imread('messi.jpg',0)
img2 = img.copy()
template = cv2.imread('face.png',0)
w, h = template.shape[::-1]
# All the 6 methods for comparison in a list
methods = ['cv2.TM_CCOEFF', 'cv2.TM_CCOEFF_NORMED', 'cv2.TM_CCORR',
'cv2.TM_CCORR_NORMED', 'cv2.TM_SQDIFF', 'cv2.TM_SQDIFF_NORMED']
for meth in methods:
img = img2.copy()
method = eval(meth)
# Apply template Matching
res = cv2.matchTemplate(img,template,method)
min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(res)
# If the method is TM_SQDIFF or TM_SQDIFF_NORMED, take minimum
if method in [cv2.TM_SQDIFF, cv2.TM_SQDIFF_NORMED]:
top_left = min_loc
else:
top_left = max_loc
bottom_right = (top_left[0] + w, top_left[1] + h)
cv2.rectangle(img,top_left, bottom_right, 255, 2)
plt.subplot(121),plt.imshow(res,cmap = 'gray')
plt.title('Matching Result'), plt.xticks([]), plt.yticks([])
plt.subplot(122),plt.imshow(img,cmap = 'gray')
plt.title('Detected Point'), plt.xticks([]), plt.yticks([])
plt.suptitle(meth)
plt.show()
示例13: plotSummaryBar
def plotSummaryBar(library, num, eventNames, sizes, times, events):
import numpy as np
import matplotlib.pyplot as plt
eventColors = ['b', 'g', 'r', 'y']
arches = sizes.keys()
names = []
N = len(sizes[arches[0]])
width = 0.2
ind = np.arange(N) - 0.25
bars = {}
for arch in arches:
bars[arch] = []
bottom = np.zeros(N)
for event, color in zip(eventNames, eventColors):
names.append(arch+' '+event)
times = np.array(events[arch][event])[:,0]
bars[arch].append(plt.bar(ind, times, width, color=color, bottom=bottom))
bottom += times
ind += 0.3
plt.xlabel('Number of Dof')
plt.ylabel('Time (s)')
plt.title('GPU vs. CPU Performance on '+library+' Example '+str(num))
plt.xticks(np.arange(N), map(str, sizes[arches[0]]))
#plt.yticks(np.arange(0,81,10))
#plt.legend( (p1[0], p2[0]), ('Men', 'Women') )
plt.legend([bar[0] for bar in bars[arches[0]]], eventNames, 'upper right', shadow = True)
plt.show()
return
示例14: test_rotated_labels_parameters_different_values
def test_rotated_labels_parameters_different_values(x_tick_label_width,
y_tick_label_width):
fig, ax = __plot()
plt.xticks(ha='left', rotation=90)
plt.yticks(ha='left', rotation=90)
ax.xaxis.get_majorticklabels()[0].set_rotation(20)
ax.yaxis.get_majorticklabels()[0].set_horizontalalignment('right')
# convert to tikz file
_, tmp_base = tempfile.mkstemp()
tikz_file = tmp_base + '_tikz.tex'
extra_dict = {}
if x_tick_label_width:
extra_dict['x tick label text width'] = x_tick_label_width
if y_tick_label_width:
extra_dict['y tick label text width'] = y_tick_label_width
matplotlib2tikz.save(
tikz_file,
figurewidth='7.5cm',
extra_axis_parameters=extra_dict
)
# close figure
plt.close(fig)
# delete file
os.unlink(tikz_file)
示例15: plot_head_map
def plot_head_map(mma, target_labels, source_labels):
fig, ax = plt.subplots()
heatmap = ax.pcolor(mma, cmap=plt.cm.Blues)
# put the major ticks at the middle of each cell
ax.set_xticks(numpy.arange(mma.shape[1])+0.5, minor=False)
ax.set_yticks(numpy.arange(mma.shape[0])+0.5, minor=False)
# without this I get some extra columns rows
# http://stackoverflow.com/questions/31601351/why-does-this-matplotlib-heatmap-have-an-extra-blank-column
ax.set_xlim(0, int(mma.shape[1]))
ax.set_ylim(0, int(mma.shape[0]))
# want a more natural, table-like display
ax.invert_yaxis()
ax.xaxis.tick_top()
# source words -> column labels
ax.set_xticklabels(source_labels, minor=False)
# target words -> row labels
ax.set_yticklabels(target_labels, minor=False)
plt.xticks(rotation=45)
#plt.tight_layout()
plt.show()