本文整理汇总了Python中matplotlib.pyplot.barh函数的典型用法代码示例。如果您正苦于以下问题:Python barh函数的具体用法?Python barh怎么用?Python barh使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了barh函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: plot
def plot(data, reverse=False):
if reverse:
data.reverse()
r = range(len(data))
plt.barh(r, [d[1] for d in data])
plt.yticks(r, [d[0] for d in data])
plt.show()
示例2: followsPicture
def followsPicture(mp):
val = []
label = []
lst0 = mp.keys()
#print lst0
lst1 = mp.values()
if len(lst1) > 10:
num = 10
else:
num = len(lst1)
while (num != 0):
i = lst1.index(max(lst1))
label.append(lst0[i])
#print type(lst1[i])
val.append(int(lst1[i]))
lst0.pop(i)
lst1.pop(i)
num -= 1
pos = np.arange(10) + .5
plt.figure(1)
plt.barh(pos,val,align='center')
plt.yticks(pos,label)
plt.xlabel(u'粉丝数目')
string = u"统计人数:" + str(len(mp.keys()))
plt.title(string)
plt.show()
示例3: make_entity_plot
def make_entity_plot(filename, title, fixed_noip, fixed_ip, dynamic_noip, dynamic_ip):
plt.figure(figsize=(12,5))
plt.title("Settings comparison - " + title)
plt.xlabel('Time (ms)', fontsize=12)
plt.xlim([0,62000])
x = 0
barwidth = 0.5
bargroupspacing = 1.5
fixed_noip_mean,fixed_noip_conf = conf_stats(fixed_noip)
fixed_ip_mean,fixed_ip_conf = conf_stats(fixed_ip)
dynamic_noip_mean,dynamic_noip_conf = conf_stats(dynamic_noip)
dynamic_ip_mean,dynamic_ip_conf = conf_stats(dynamic_ip)
values = [fixed_noip_mean,fixed_ip_mean,dynamic_noip_mean, dynamic_ip_mean]
errs = [fixed_noip_conf,fixed_ip_conf,dynamic_noip_conf, dynamic_ip_conf]
y_pos = numpy.arange(len(values))
plt.barh(y_pos, values, xerr=errs, align='center', color=['r', 'b', 'r', 'b'], ecolor='black', alpha=0.7)
plt.yticks(y_pos, ["Fixed | no I.P.", "Fixed | I.P.", "Dynamic | no I.P.", "Dynamic | I.P."])
plt.savefig(output_file(filename))
plt.clf()
示例4: plot_hist_over_category
def plot_hist_over_category(category_names_avgs_sem_triple_list, plt_number, x_label, groups, printse):
height_factor = 0.5
ind = np.linspace(0,len(category_names_avgs_sem_triple_list)*height_factor, num = len(category_names_avgs_sem_triple_list))
width = 0.25
fig = plt.figure(figsize=(15.5, 10),dpi=800)
plot = fig.add_subplot(111)
plot.tick_params(axis='y', which='major', labelsize= 10 )
plot.tick_params(axis='x', which='major', labelsize= 10 )
length = len(category_names_avgs_sem_triple_list)
l = 0
it = cycle(["#CCD64B","#C951CA","#CF4831","#90D0D2","#33402A","#513864",
"#C84179","#DA983D","#CA96C4","#53913D","#CEC898","#70D94C",
"#CB847E","#796ACB","#74D79C","#60292F","#6C93C4","#627C76",
"#865229","#838237"])
color=[next(it) for i in range(length)]
if printse:
p1 = plt.barh(ind, [x[1] for x in category_names_avgs_sem_triple_list], color=color,align='center', height= height_factor, xerr= [x[2] for x in category_names_avgs_sem_triple_list])
else:
p1 = plt.barh(ind, [x[1] for x in category_names_avgs_sem_triple_list], color=color,align='center', height= height_factor)
plt.yticks(ind, [x[0] for x in category_names_avgs_sem_triple_list])
plt.xlabel(x_label)
plt.ylabel("Categories")
plt.subplots_adjust(bottom=0.15, left=0.14,right=0.95,top=0.95)
plt.ylim([ind.min()- height_factor, ind.max() + height_factor])
plt.xlim(min([x[1] for x in category_names_avgs_sem_triple_list])-height_factor, max([x[1] for x in category_names_avgs_sem_triple_list])+height_factor)
try:
os.makedirs(plot_path+x_label)
except OSError as exception:
if exception.errno != errno.EEXIST:
raise
print("da wirds gespeichert:")
print(plot_path+x_label+"/"+str(plt_number)+"groups_"+str(groups))
plt.savefig(plot_path+x_label+"/"+str(plt_number)+"groups_"+str(groups))
plt.close()
示例5: barGraph
def barGraph(namesByYear): # Bargraph generator
"""Plotting function used to create bar graphs."""
plt.title('Births By Name For Input Year')
plt.xlabel('Births')
plt.yticks(range(len(namesByYear), 0, -1), [n for (n, t) in namesByYear])
plt.barh(range(len(namesByYear), 0, -1), [t for (n, t) in namesByYear])
plt.show()
示例6: PlotFeaturesImportance
def PlotFeaturesImportance(X,y,featureNames,dataName):
'''
Plot the relative contribution/importance of the features.
Best to reduce to top X features first - for interpretability
Code example from:
http://bugra.github.io/work/notes/2014-11-22/an-introduction-to-supervised-learning-scikit-learn/
'''
gbc = GradientBoostingClassifier(n_estimators=40)
gbc.fit(X, y)
# Get Feature Importance from the classifier
feature_importance = gbc.feature_importances_
# Normalize The Features
feature_importance = 100 * (feature_importance / feature_importance.max())
sorted_idx = numpy.argsort(feature_importance)
pos = numpy.arange(sorted_idx.shape[0]) + 4.5
# pos = numpy.arange(sorted_idx.shape[0])
# plt.figure(figsize=(16, 12))
plt.figure(figsize=(14, 9), dpi=250)
plt.barh(pos, feature_importance[sorted_idx], align='center', color='#7A68A6')
#plt.yticks(pos, numpy.asanyarray(df.columns.tolist())[sorted_idx]) #ORIG
plt.yticks(pos, numpy.asanyarray(featureNames)[sorted_idx])
plt.xlabel('Relative Importance')
plt.title('%s: Top Features' %(dataName))
plt.grid('off')
plt.ion()
plt.show()
plt.savefig(str(dataName)+'TopFeatures.png',dpi=200)
示例7: plot_feature_importances_cancer
def plot_feature_importances_cancer(model):
n_features = cancer.data.shape[1]
plt.barh(range(n_features), model.feature_importances_, align='center')
plt.yticks(np.arange(n_features), cancer.feature_names)
plt.xlabel("특성 중요도")
plt.ylabel("특성")
plt.ylim(-1, n_features)
示例8: plot_zrtt_treshold
def plot_zrtt_treshold(data, output_path):
threshold = 1
gateways, zrtts = [], []
for hop in data:
ip, pais, zrtt = hop
gateways.append(ip+"\n"+pais)
zrtts.append(float(zrtt))
gateways.reverse()
zrtts.reverse()
fig = plt.figure()
y_pos = np.arange(len(gateways))
plt.barh(y_pos, zrtts, align='center', alpha=0.4)
plt.yticks(y_pos, gateways, horizontalalignment='right', fontsize=9)
plt.title('ZRTTs para cada hop')
plt.xlabel('ZRTT')
plt.ylabel('Hop')
# Line at y=0
plt.vlines(0, -1, len(gateways), alpha=0.4)
# ZRTT threshold
plt.vlines(threshold, -1, len(gateways), linestyle='--', color='b', alpha=0.4)
plt.text(threshold, len(gateways) - 1, 'Umbral', rotation='vertical',
verticalalignment='top', horizontalalignment='right')
fig.set_size_inches(6, 9)
plt.tight_layout()
plt.savefig(output_path, dpi=1000, box_inches='tight')
示例9: bii_hbar
def bii_hbar(group,code,in_data):
[trust,res,div,bel,collab,resall,comfort,iz,score] = in_data
plt.figure()
if len(code) == 2 and not isinstance(code, basestring):
code = code[0] + " " + code[1]
val = [mean(trust),mean(res),mean(div),mean(bel),mean(collab),mean(resall),mean(comfort),mean(iz)][-1::-1]
pos = arange(8) # the bar centers on the y axis
plt.plot((mean(score), mean(score)), (-1, 8), 'g',label='Average',linewidth=3)
#plt.barh(pos,val, xerr=err, ecolor='r', align='center',label='Score')
plt.barh(pos,val, align='center', label='Score')
if group:
err = [std(trust),std(res),std(div),std(bel),std(collab),std(resall),std(comfort),std(iz)][-1::-1]
plt.errorbar(val,pos, xerr=err, label="St Dev", color='r',fmt='o')
lgd = plt.legend(loc='upper center', shadow=True, fontsize='x-large',bbox_to_anchor=(1.1, 1.1),borderaxespad=0.)
plt.yticks(pos, (('Tru', 'Res', 'Div', 'Ment Str','Collab', 'Res All', 'Com Zone', 'In Zone'))[-1::-1])
plt.xlabel('Score')
plt.title('Results for ' + code, fontweight='bold', y=1.01)
plt.xlabel(r'$\mathrm{Total \ Innovation \ Index \ Score:}\ %.3f$' %(mean(score)),fontsize='18')
axes = plt.gca()
axes.set_xlim([0,10])
# plt.legend((score_all,score_mean), ('Score','Mean'),bbox_to_anchor=(1.3, 1.3),borderaxespad=0.)
file_name = "hbar"
path_name = "static/%s" %file_name
#path_name = "/Users/johanenglarsson/bii/mod/static/%s" %file_name
plt.savefig(path_name, bbox_extra_artists=(lgd,), bbox_inches='tight')
示例10: plot_unique_by_date
def plot_unique_by_date(alignment_summaries, metadata):
plt.figure(figsize=(8, 5.5))
df_meta = pd.DataFrame.from_csv(metadata)
df_meta['Date Produced'] = pd.to_datetime(df_meta['Date Produced'])
alndata = []
for summary in alignment_summaries:
alndata.append(simpleseq.sam.get_alignment_metadata(summary))
unique = pd.Series(np.array([s['uniq_rate'] for s in alndata]),
index=alignment_summaries)
# plot unique alignments
index = df_meta.index.intersection(unique.index)
order = df_meta.loc[index].sort(columns='Date Produced', ascending=False).index
left = np.arange(len(index))
height = unique.ix[order]
width = 0.9
plt.barh(left, height, width)
plt.yticks(left + 0.5, order, fontsize=10)
ymin, ymax = 0, len(left)
plt.ylim((ymin, ymax))
plt.xlabel('percentage')
plt.title('comparative alignment summary')
plt.ylabel('time (descending)')
# plot klein in-drop line
plt.vlines(unique['Klein_in_drop'], ymin, ymax, color='indianred', linestyles='--')
sns.despine()
plt.tight_layout()
示例11: plot_freqs
def plot_freqs(freqs, n=30):
# plot top n words and their frequencies from greatest to least
if n > len(freqs):
n = len(freqs)
# sort in decreasing order
words_sorted = sorted(freqs, key=freqs.get, reverse=True)
freqs_sorted = [freqs[word] for word in words_sorted[:n]]
# plot
fig = plt.figure(figsize=(6,4))
beautify_plot(fig)
plt.ylim(0,n)
#plt.xlim(0,MAX_OF_FREQS)
# Plot in horizontal bars in descending order
bar_locs = np.arange(n, 0, -1)
bar_width = 1.0
plt.barh(bar_locs, freqs_sorted, height=bar_width,
align='center', color=t20[0], alpha=0.8, linewidth=0)
# Label each bar with its word
plt.yticks(range(n-1,-1,-1), words_sorted)
plt.xlabel('Word Frequency (per billlion)')
plt.title('Top ' + str(n) + ' words used in Billboard 100 Songs')
plt.show()
示例12: plot_feature_importance
def plot_feature_importance(regressor, params, X_test, y_test):
test_score = np.zeros((params['n_estimators'],), dtype = np.float64)
for i, y_pred in enumerate(regressor.staged_predict(X_test)):
test_score[i] = regressor.loss_(y_test, y_pred)
plt.figure(figsize = (12, 6))
plt.subplot(1, 2, 1)
plt.title('MAE Prediction vs. Actual (USD) ')
plt.plot(np.arange(params['n_estimators']) + 1, regressor.train_score_, 'b-', label = 'Training set Deviance')
plt.plot(np.arange(params['n_estimators']) + 1, test_score, 'r-', label = 'Test set deviance')
plt.legend(loc='upper right')
plt.xlabel('Boosting Iterations')
plt.ylabel('Mean absolute error')
#plot feature importance
feature_importance = regressor.feature_importances_
#normalize
feature_importance = 100.0 * (feature_importance / feature_importance.max())
sorted_idx = np.argsort(feature_importance)
pos = np.arange(sorted_idx.shape[0]) + .5
plt.subplot(1, 2, 2)
plt.barh(pos, feature_importance[sorted_idx], align='center')
feature_names = np.array(feature_cols)
plt.yticks(pos, feature_names[sorted_idx])
plt.xlabel('Relative importance')
plt.title('Variable Importance')
plt.show()
示例13: lookAtVoltages
def lookAtVoltages(voltagetraces,startRec,plotTime):
voltage_means=zeros(len(voltagetraces))
for n in range(len(voltagetraces)):
voltage_means[n]=mean(voltagetraces[n])
print 'mean voltages (mean,std.dev):'
meanV=mean(voltage_means)
stdDev=sqrt(var(voltage_means))
print meanV,stdDev
fig=plt.figure()
ax1=fig.add_axes([.15,.1,.7,.8])
plotVolts=zeros([len(voltList),int(plotTime)])
for i in range(len(voltList)):
plotVolts[i,:]=voltagetraces[i][0:int(plotTime)]
plt.plot(range(int(startRec),int(plotTime)+int(startRec)),voltagetraces[i][0:int(plotTime)],color='0.75',label=str(voltList[i]))
plt.plot(range(int(startRec),int(plotTime)+int(startRec)),sum(plotVolts,0)/len(voltList),'r',linewidth=3)
plt.ylabel("rate [Hz]")
plt.xlabel("time [ms]")
bins=arange(plotVolts.min(),plotVolts.max(),(plotVolts.max()-plotVolts.min())/50)
hist=zeros(len(bins)-1)
for n in range(int(plotTime)):
hist=hist+histogram(plotVolts[:,n], bins, new=True, normed=False)[0]
plt.plot(range(int(startRec),int(plotTime)+int(startRec)),zeros(int(plotTime)),'k:',linewidth=3)
ax2=fig.add_axes([.85,.1,.1,.8])
ax2.set_axis_off()
plt.barh(bins[:-1],hist[:],height=(bins[1]-bins[0]),edgecolor='b')
ax1.set_ylim(plotVolts.min(),plotVolts.max())
ax2.set_ylim(ax1.get_ylim())
return fig,meanV,stdDev
示例14: barh_plot
def barh_plot():
"""
barh plot
"""
# 生成测试数据
means_men = (20, 35, 30, 35, 27)
means_women = (25, 32, 34, 20, 25)
# 设置标题
plt.title("横向柱状图", fontproperties=myfont)
# 设置相关参数
index = np.arange(len(means_men))
bar_height = 0.35
# 画柱状图(水平方向)
plt.barh(index, means_men, height=bar_height, alpha=0.2, color="b", label="Men")
plt.barh(index+bar_height, means_women, height=bar_height, alpha=0.8, color="r", label="Women")
plt.legend(loc="upper right", shadow=True)
# 设置柱状图标示
for x, y in zip(index, means_men):
plt.text(y+0.3, x, y, ha="left", va="center")
for x, y in zip(index, means_women):
plt.text(y+0.3, x+bar_height, y, ha="left", va="center")
# 设置刻度范围/坐标轴名称等
plt.xlim(0, 45)
plt.xlabel("Scores")
plt.ylabel("Group")
plt.yticks(index+(bar_height/2), ("A", "B", "C", "D", "E"))
# 图形显示
plt.show()
return
示例15: plot
def plot(results, total_a, total_b, label_a, label_b, outputFile=None):
all_rules = sorted(results, key=lambda v: (-len(v['item']), round(abs(v['count_a'] / total_a - v['count_b'] / total_b), 2), round(v['count_a'] / total_a, 2)))
values_a = [100 * rule['count_a'] / total_a for rule in all_rules]
values_b = [100 * rule['count_b'] / total_b for rule in all_rules]
plt.rc('figure', autolayout=True)
plt.rc('font', size=22)
fig, ax = plt.subplots(figsize=(24, 18))
index = range(len(all_rules))
bar_width = 0.35
if label_a.startswith('_'):
label_a = ' ' + label_a
if label_b.startswith('_'):
label_b = ' ' + label_b
bar_a = plt.barh(index, values_a, bar_width, color='b', label=label_a)
bar_b = plt.barh([i + bar_width for i in index], values_b, bar_width, color='r', label=label_b)
plt.xlabel('Support')
plt.ylabel('Rule')
plt.title('Most interesting deviations')
plt.yticks([i + bar_width for i in index], [rule_to_str(rule['item']) for rule in all_rules])
if len(all_rules) > 0:
plt.legend(handles=[bar_b, bar_a], loc='best')
if outputFile is not None:
plt.savefig(outputFile)
else:
plt.show()
plt.close(fig)