如何使用Python修改matplotlib.pyplot.colorbar的位置以對齊主圖
問題描述
像這樣的圖,我想把右邊的colorbar設(shè)置成和主圖一樣高度
方法
0. plt.colorbar參數(shù)介紹
1. plt.colorbar(im, fraction=0.046, pad=0.04, shrink=1.0)
fraction可以從0.035-0.046調(diào)節(jié)以找到合適大小
但當(dāng)圖像的長、高對比過大時,可能不起作用
2. make_axes_locatable
這是matplotlib包里的一個函數(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(會報錯),如cartopy的GeoAxes
3. make_axes_locatables 升級版
https://stackoverflow.com/questions/18195758/set-matplotlib-colorbar-size-to-match-graph @Matthias
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)
4. 手動給colorbar添加一個axe
https://stackoverflow.com/questions/18195758/set-matplotlib-colorbar-size-to-match-graph @Fei Yao
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)
效果展示
總結(jié)
到此這篇關(guān)于如何使用Python修改matplotlib.pyplot.colorbar的位置以對齊主圖的文章就介紹到這了,更多相關(guān)Python修改matplotlib.pyplot.colorbar位置內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Python實(shí)現(xiàn)實(shí)時顯示進(jìn)度條的6種方法
相信大家對進(jìn)度條一定不陌生了,很多安裝或者下載都會出現(xiàn)進(jìn)度條,本文主要介紹了Python實(shí)現(xiàn)實(shí)時顯示進(jìn)度條的6種方法,具有一定的參考價值,感興趣的可以了解一下2021-12-12Python和JS反爬之解決反爬參數(shù)?signKey
這篇文章主要介紹了Python和JS反爬之解決反爬參數(shù)?signKey,Python?反爬中有一大類,叫做字體反爬,核心的理論就是通過字體文件或者?CSS?偏移,接下來文章的詳細(xì)介紹,需要的小伙伴可以參考一下2022-05-05如何用Python中Tushare包輕松完成股票篩選(詳細(xì)流程操作)
這篇文章主要介紹了如何用Python中Tushare包輕松完成股票篩選(詳細(xì)流程操作),文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2021-03-03使用Python的pencolor函數(shù)實(shí)現(xiàn)漸變色功能
這篇文章主要介紹了使用Python的pencolor函數(shù)實(shí)現(xiàn)漸變色功能,本文通過實(shí)例代碼給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2021-03-03詳解LyScript 內(nèi)存掃描與查殼實(shí)現(xiàn)
這篇文章主要為大家介紹了詳解LyScript 內(nèi)存掃描與查殼實(shí)現(xiàn)詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-09-09