development

Matplotlib 컬러 바 크기를 그래프와 일치하도록 설정

big-blog 2020. 7. 2. 07:19
반응형

Matplotlib 컬러 바 크기를 그래프와 일치하도록 설정


이 같은 imshow 그래프의 컬러 막대를 그래프와 동일한 높이로 만들 수는 없습니다. 사실 후에 Photoshop을 사용하지 않는 것입니다. 높이를 맞추려면 어떻게해야합니까?컬러 바 크기 불일치의 예


matplotlib AxisDivider를 사용하면이 작업을 쉽게 수행 할 수 있습니다 .

연결된 페이지의 예제는 하위 플롯을 사용하지 않고 작동합니다.

import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1 import make_axes_locatable
import numpy as np

plt.figure()
ax = plt.gca()
im = ax.imshow(np.arange(100).reshape((10,10)))

# create an axes on the right side of ax. The width of cax will be 5%
# of ax and the padding between cax and ax will be fixed at 0.05 inch.
divider = make_axes_locatable(ax)
cax = divider.append_axes("right", size="5%", pad=0.05)

plt.colorbar(im, cax=cax)

여기에 이미지 설명을 입력하십시오


이 조합 (및이 값에 가까운 값)은 디스플레이의 크기에 관계없이 컬러 막대를 플롯에 맞게 유지하는 데 "마 법적으로"작동하는 것 같습니다.

plt.colorbar(im,fraction=0.046, pad=0.04)

또한 플롯을 사각형에서 벗어날 수있는 축을 공유 할 필요가 없습니다.


@bogatron은 이미 올바른 높이를 생성하는 matplotlib docs 에서 제안한 답변을 제공 했지만 다른 문제가 발생합니다. 이제 색상 막대의 너비와 색상 막대와 플롯 사이의 간격이 플롯 너비에 따라 변경됩니다. 즉, 컬러 바의 종횡비가 더 이상 고정되지 않습니다.

올바른 높이 주어진 종횡비를 모두 얻으려면 신비한 axes_grid1모듈을 조금 더 깊이 파고 들어야 합니다.

import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1 import make_axes_locatable, axes_size
import numpy as np

aspect = 20
pad_fraction = 0.5

ax = plt.gca()
im = ax.imshow(np.arange(200).reshape((20, 10)))
divider = make_axes_locatable(ax)
width = axes_size.AxesY(ax, aspect=1./aspect)
pad = axes_size.Fraction(pad_fraction, width)
cax = divider.append_axes("right", size=width, pad=pad)
plt.colorbar(im, cax=cax)

이 지정은 유의 년 Colorbar의 WRT는 높이 (받는 반면에 플롯을 은 전과 같이, 도면 중).

The spacing between colorbar and plot can now be specified as a fraction of the width of the colorbar, which is IMHO a much more meaningful number than a fraction of the figure width.

컬러 바가있는 이미지 플롯

UPDATE:

I created an IPython notebook on the topic, where I packed the above code into an easily re-usable function:

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)

It can be used like this:

im = plt.imshow(np.arange(200).reshape((20, 10)))
add_colorbar(im)

When you create the colorbar try using the fraction and/or shrink parameters.

From the documents:

fraction 0.15; fraction of original axes to use for colorbar

shrink 1.0; fraction by which to shrink the colorbar


All the above solutions are good, but I like @Steve's and @bejota's the best as they do not involve fancy calls and are universal.

By universal I mean that works with any type of axes including GeoAxes. For example, it you have projected axes for mapping:

projection = cartopy.crs.UTM(zone='17N')
ax = plt.axes(projection=projection)
im = ax.imshow(np.arange(200).reshape((20, 10)))

a call to

cax = divider.append_axes("right", size=width, pad=pad)

will fail with: KeyException: map_projection

Therefore, the only universal way of dealing colorbar size with all types of axes is:

ax.colorbar(im, fraction=0.046, pad=0.04)

Work with fraction from 0.035 to 0.046 to get your best size. However, the values for the fraction and paddig will need to be adjusted to get the best fit for your plot and will differ depending if the orientation of the colorbar is in vertical position or horizontal.


I appreciate all the answers above. However, like some answers and comments pointed out, the axes_grid1 module cannot address GeoAxes, whereas adjusting fraction, pad, shrink, and other similar parameters cannot necessarily give the very precise order, which really bothers me. I believe that giving the colorbar its own axes might be a better solution to address all the issues that have been mentioned.

Code

import matplotlib.pyplot as plt
import numpy as np

fig=plt.figure()
ax = plt.gca()
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)

Result

여기에 이미지 설명을 입력하십시오

참고 URL : https://stackoverflow.com/questions/18195758/set-matplotlib-colorbar-size-to-match-graph

반응형