您好,登錄后才能下訂單哦!
本篇內(nèi)容主要講解“怎么使用Python修改matplotlib.pyplot.colorbar的位置以對(duì)齊主圖”,感興趣的朋友不妨來看看。本文介紹的方法操作簡(jiǎn)單快捷,實(shí)用性強(qiáng)。下面就讓小編來帶大家學(xué)習(xí)“怎么使用Python修改matplotlib.pyplot.colorbar的位置以對(duì)齊主圖”吧!
像這樣的圖,我想把右邊的colorbar設(shè)置成和主圖一樣高度
fraction可以從0.035-0.046調(diào)節(jié)以找到合適大小
但當(dāng)圖像的長(zhǎng)、高對(duì)比過大時(shí),可能不起作用
這是matplotlib包里的一個(gè)函數(shù)
from mpl_toolkits.axes_grid1 import make_axes_locatable im = plt.imshow(data) divider = make_axes_locatable(plt.gca()) cax = divider.append_axes("right", size="5%", pad="3%") plt.colorbar(im, cax=cax)
不適用于有投影參數(shù)的axe(會(huì)報(bào)錯(cuò)),如cartopy的GeoAxes
import matplotlib.pyplot as plt from mpl_toolkits import axes_grid1 def add_colorbar(im, aspect=20, pad_fraction=0.5, **kwargs): """Add a vertical color bar to an image plot.""" divider = axes_grid1.make_axes_locatable(im.axes) width = axes_grid1.axes_size.AxesY(im.axes, aspect=1./aspect) pad = axes_grid1.axes_size.Fraction(pad_fraction, width) current_ax = plt.gca() cax = divider.append_axes("right", size=width, pad=pad) plt.sca(current_ax) return im.axes.figure.colorbar(im, cax=cax, **kwargs)
用法示例
im = plt.imshow(np.arange(200).reshape((20, 10))) add_colorbar(im)
import matplotlib.pyplot as plt import numpy as np fig=plt.figure() ax = plt.axes() im = ax.imshow(np.arange(100).reshape((10,10))) # Create an axes for colorbar. The position of the axes is calculated based on the position of ax. # You can change 0.01 to adjust the distance between the main image and the colorbar. # You can change 0.02 to adjust the width of the colorbar. # This practice is universal for both subplots and GeoAxes. cax = fig.add_axes([ax.get_position().x1+0.01,ax.get_position().y0,0.02,ax.get_position().height]) plt.colorbar(im, cax=cax) # Similar to fig.colorbar(im, cax = cax)
效果展示
到此,相信大家對(duì)“怎么使用Python修改matplotlib.pyplot.colorbar的位置以對(duì)齊主圖”有了更深的了解,不妨來實(shí)際操作一番吧!這里是億速云網(wǎng)站,更多相關(guān)內(nèi)容可以進(jìn)入相關(guān)頻道進(jìn)行查詢,關(guān)注我們,繼續(xù)學(xué)習(xí)!
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。