Movatterモバイル変換


[0]ホーム

URL:


  1. matplotlib-gallery
  2. ipynb
Notebook

Sebastian Raschka

back to thematplotlib-gallery athttps://github.com/rasbt/matplotlib-gallery

In [1]:
%load_ext watermark
In [2]:
%watermark -u -v -d -p matplotlib,numpy
last updated: 2016-03-12 CPython 3.5.1IPython 4.0.3matplotlib 1.5.1numpy 1.10.4

In [3]:
%matplotlib inline


Bar plots in Matplotlib

Sections



Bar plot with error bars

[back to top]

In [6]:
importmatplotlib.pyplotasplt# input datamean_values=[1,2,3]variance=[0.2,0.4,0.5]bar_labels=['bar 1','bar 2','bar 3']# plot barsx_pos=list(range(len(bar_labels)))plt.bar(x_pos,mean_values,yerr=variance,align='center',alpha=0.5)plt.grid()# set height of the y-axismax_y=max(zip(mean_values,variance))# returns a tuple, here: (3, 5)plt.ylim([0,(max_y[0]+max_y[1])*1.1])# set axes labels and titleplt.ylabel('variable y')plt.xticks(x_pos,bar_labels)plt.title('Bar plot with error bars')plt.show()#plt.savefig('./my_plot.png')


Horizontal bar plot with error bars

[back to top]

In [20]:
frommatplotlibimportpyplotaspltimportnumpyasnp# input datamean_values=[1,2,3]std_dev=[0.2,0.4,0.5]bar_labels=['bar 1','bar 2','bar 3']fig=plt.figure(figsize=(8,6))# plot barsy_pos=np.arange(len(mean_values))y_pos=[xforxiny_pos]plt.yticks(y_pos,bar_labels,fontsize=10)plt.barh(y_pos,mean_values,xerr=std_dev,align='center',alpha=0.4,color='g')# annotation and labelsplt.xlabel('measurement x')t=plt.title('Bar plot with standard deviation')plt.ylim([-1,len(mean_values)+0.5])plt.xlim([0,4])plt.grid()plt.show()


Back-to-back bar plot

[back to top]

In [19]:
frommatplotlibimportpyplotaspltimportnumpyasnp# input dataX1=np.array([1,2,3])X2=np.array([2,2,3])bar_labels=['bar 1','bar 2','bar 3']fig=plt.figure(figsize=(8,6))# plot barsy_pos=np.arange(len(X1))y_pos=[xforxiny_pos]plt.yticks(y_pos,bar_labels,fontsize=10)plt.barh(y_pos,X1,align='center',alpha=0.4,color='g')# we simply negate the values of the numpy array for# the second bar:plt.barh(y_pos,-X2,align='center',alpha=0.4,color='b')# annotation and labelsplt.xlabel('measurement x')t=plt.title('Bar plot with standard deviation')plt.ylim([-1,len(X1)+0.1])plt.xlim([-max(X2)-1,max(X1)+1])plt.grid()plt.show()


Grouped bar plot

[back to top]

In [39]:
importmatplotlib.pyplotasplt# Input datagreen_data=[1,2,3]blue_data=[3,2,1]red_data=[2,3,3]labels=['group 1','group 2','group 3']# Setting the positions and width for the barspos=list(range(len(green_data)))width=0.2# Plotting the barsfig,ax=plt.subplots(figsize=(8,6))plt.bar(pos,green_data,width,alpha=0.5,color='g',label=labels[0])plt.bar([p+widthforpinpos],blue_data,width,alpha=0.5,color='b',label=labels[1])plt.bar([p+width*2forpinpos],red_data,width,alpha=0.5,color='r',label=labels[2])# Setting axis labels and ticksax.set_ylabel('y-value')ax.set_title('Grouped bar plot')ax.set_xticks([p+1.5*widthforpinpos])ax.set_xticklabels(labels)# Setting the x-axis and y-axis limitsplt.xlim(min(pos)-width,max(pos)+width*4)plt.ylim([0,max(green_data+blue_data+red_data)*1.5])# Adding the legend and showing the plotplt.legend(['green','blue','red'],loc='upper left')plt.grid()plt.show()


Stacked bar plot

[back to top]

In [36]:
importmatplotlib.pyplotaspltblue_data=[100,120,140]red_data=[150,120,190]green_data=[80,70,90]f,(ax1,ax2)=plt.subplots(1,2,figsize=(10,5))bar_width=0.5# positions of the left bar-boundariesbar_l=[i+1foriinrange(len(blue_data))]# positions of the x-axis ticks (center of the bars as bar labels)tick_pos=[i+(bar_width/2)foriinbar_l]##################### Absolute count###################ax1.bar(bar_l,blue_data,width=bar_width,label='blue data',alpha=0.5,color='b')ax1.bar(bar_l,red_data,width=bar_width,bottom=blue_data,label='red data',alpha=0.5,color='r')ax1.bar(bar_l,green_data,width=bar_width,bottom=[i+jfori,jinzip(blue_data,red_data)],label='green data',alpha=0.5,color='g')plt.sca(ax1)plt.xticks(tick_pos,['category 1','category 2','category 3'])ax1.set_ylabel("Count")ax1.set_xlabel("")plt.legend(loc='upper left')plt.xlim([min(tick_pos)-bar_width,max(tick_pos)+bar_width])plt.grid()# rotate axis labelsplt.setp(plt.gca().get_xticklabels(),rotation=45,horizontalalignment='right')############## Percent############totals=[i+j+kfori,j,kinzip(blue_data,red_data,green_data)]blue_rel=[i/j*100fori,jinzip(blue_data,totals)]red_rel=[i/j*100fori,jinzip(red_data,totals)]green_rel=[i/j*100fori,jinzip(green_data,totals)]ax2.bar(bar_l,blue_rel,label='blue data',alpha=0.5,color='b',width=bar_width)ax2.bar(bar_l,red_rel,bottom=blue_rel,label='red data',alpha=0.5,color='r',width=bar_width)ax2.bar(bar_l,green_rel,bottom=[i+jfori,jinzip(blue_rel,red_rel)],label='green data',alpha=0.5,color='g',width=bar_width)plt.sca(ax2)plt.xticks(tick_pos,['category 1','category 2','category 3'])ax2.set_ylabel("Percentage")ax2.set_xlabel("")plt.xlim([min(tick_pos)-bar_width,max(tick_pos)+bar_width])plt.grid()# rotate axis labelsplt.setp(plt.gca().get_xticklabels(),rotation=45,horizontalalignment='right')plt.show()


Bar plot with plot labels/text 1

[back to top]

In [17]:
frommatplotlibimportpyplotaspltimportnumpyasnpdata=range(200,225,5)bar_labels=['a','b','c','d','e']fig=plt.figure(figsize=(10,8))# plot barsy_pos=np.arange(len(data))plt.yticks(y_pos,bar_labels,fontsize=16)bars=plt.barh(y_pos,data,align='center',alpha=0.4,color='g')# annotation and labelsforb,dinzip(bars,data):plt.text(b.get_width()+b.get_width()*0.08,b.get_y()+b.get_height()/2,'{0:.2%}'.format(d/min(data)),ha='center',va='bottom',fontsize=12)plt.xlabel('X axis label',fontsize=14)plt.ylabel('Y axis label',fontsize=14)t=plt.title('Bar plot with plot labels/text',fontsize=18)plt.ylim([-1,len(data)+0.5])plt.vlines(min(data),-1,len(data)+0.5,linestyles='dashed')plt.grid()plt.show()


Bar plot with plot labels/text 2

[back to top]

In [8]:
importmatplotlib.pyplotasplt# input datamean_values=[1,2,3]bar_labels=['bar 1','bar 2','bar 3']# plot barsx_pos=list(range(len(bar_labels)))rects=plt.bar(x_pos,mean_values,align='center',alpha=0.5)# label barsdefautolabel(rects):forii,rectinenumerate(rects):height=rect.get_height()plt.text(rect.get_x()+rect.get_width()/2.,1.02*height,'%s'%(mean_values[ii]),ha='center',va='bottom')autolabel(rects)# set height of the y-axismax_y=max(zip(mean_values,variance))# returns a tuple, here: (3, 5)plt.ylim([0,(max_y[0]+max_y[1])*1.1])# set axes labels and titleplt.ylabel('variable y')plt.xticks(x_pos,bar_labels)plt.title('Bar plot with labels')plt.show()#plt.savefig('./my_plot.png')


Barplot with auto-rotated labels and text

[back to top]

In [7]:
%matplotlib inlineimportmatplotlib.pyplotaspltidx=range(4)values=[100,1000,5000,20000]labels=['category 1','category 2','category 3','category 4']fig,ax=plt.subplots(1)# Automatically align and rotate tick labels:fig.autofmt_xdate()bars=plt.bar(idx,values,align='center')plt.xticks(idx,labels)plt.tight_layout()# Add text labels to the top of the barsdefautolabel(bars):forbarinbars:height=bar.get_height()ax.text(bar.get_x()+bar.get_width()/2.,1.05*height,'%d'%int(height),ha='center',va='bottom')autolabel(bars)plt.ylim([0,25000])plt.show()


Bar plot with color gradients

[back to top]

In [21]:
importmatplotlib.pyplotaspltimportmatplotlib.colorsascolimportmatplotlib.cmascm# input datamean_values=range(10,18)x_pos=range(len(mean_values))# create colormapcmap1=cm.ScalarMappable(col.Normalize(min(mean_values),max(mean_values),cm.hot))cmap2=cm.ScalarMappable(col.Normalize(0,20,cm.hot))# plot barsplt.subplot(121)plt.bar(x_pos,mean_values,align='center',alpha=0.5,color=cmap1.to_rgba(mean_values))plt.ylim(0,max(mean_values)*1.1)plt.subplot(122)plt.bar(x_pos,mean_values,align='center',alpha=0.5,color=cmap2.to_rgba(mean_values))plt.ylim(0,max(mean_values)*1.1)plt.show()


Bar plot pattern fill

[back to top]

In [15]:
importmatplotlib.pyplotaspltpatterns=('-','+','x','\\','*','o','O','.')fig=plt.gca()# input datamean_values=range(1,len(patterns)+1)# plot barsx_pos=list(range(len(mean_values)))bars=plt.bar(x_pos,mean_values,align='center',color='white',)# set patternsforbar,patterninzip(bars,patterns):bar.set_hatch(pattern)# set axes labels and formattingfig.axes.get_yaxis().set_visible(False)plt.ylim([0,max(mean_values)*1.1])plt.xticks(x_pos,patterns)plt.show()
In [ ]:

[8]ページ先頭

©2009-2025 Movatter.jp