@@ -562,15 +562,24 @@ def clf():
562562 gcf ().clf ()
563563 draw_if_interactive ()
564564
565- def colorbar (tickfmt = '%1.1f' ):
565+ def colorbar (tickfmt = '%1.1f' , cax = None , orientation = 'vertical' ):
566566 """
567567 Create a colorbar for current mappable image (see gci)
568568
569569 tickfmt is a format string to format the colorbar ticks
570570
571+ cax is a colorbar axes instance in which the colorbar will be
572+ placed. If None, as default axesd will be created resizing the
573+ current aqxes to make room for it. If not None, the supplied axes
574+ will be used and the other axes positions will be unchanged.
575+
576+ orientation is the colorbar orientation: one of 'vertical' | 'horizontal'
571577 return value is the colorbar axes instance
572578 """
573579
580+ if orientation not in ('horizontal' , 'vertical' ):
581+ raise ValueError ('Orientation must be horizontal or vertical' )
582+
574583 mappable = gci ()
575584 if mappable is None :
576585 error_msg ('First define a mappable image (eg imshow, figimage, pcolor, scatter' )
@@ -589,25 +598,38 @@ def colorbar(tickfmt='%1.1f'):
589598 mappable .autoscale ()
590599 cmin = norm .vmin
591600 cmax = norm .vmax
592- l ,b ,w ,h = ax .get_position ()
593601
594- neww = 0.8 * w
595- ax .set_position ((l ,b ,neww ,h ))
596- cax = axes ([l + 0.9 * w , b , 0.1 * w , h ])
597- N = 200
602+ if cax is None :
603+ l ,b ,w ,h = ax .get_position ()
604+ neww = 0.8 * w
605+ ax .set_position ((l ,b ,neww ,h ))
606+ cax = axes ([l + 0.9 * w , b , 0.1 * w , h ])
607+ else :
608+ if not isinstance (cax , Axes ):
609+ raise TypeError ('Expected an Axes instance for cax' )
610+
611+ N = cmap .N
598612
599613 c = linspace (cmin , cmax , N )
600614 C = array ([c ,c ])
601615
602- coll = cax .imshow (transpose (C ), interpolation = 'nearest' ,
616+ if orientation == 'vertical' :
617+ C = transpose (C )
618+ coll = cax .imshow (C ,
619+ interpolation = 'nearest' ,
603620 origin = 'lower' ,
604621 cmap = cmap , norm = norm ,
605622 extent = (0 , 1 , cmin , cmax ))
606623 mappable .add_observer (coll )
624+
625+ if orientation == 'vertical' :
626+ cax .set_xticks ([])
627+ cax .yaxis .tick_right ()
628+ cax .yaxis .set_major_formatter (FormatStrFormatter (tickfmt ))
629+ else :
630+ cax .set_yticks ([])
631+ cax .xaxis .set_major_formatter (FormatStrFormatter (tickfmt ))
607632
608- cax .set_xticks ([])
609- cax .yaxis .tick_right ()
610- cax .yaxis .set_major_formatter (FormatStrFormatter (tickfmt ))
611633 # restore the current axes
612634 axes (ax )
613635 return cax
0 commit comments