2017-11-16 5 views
1

"플롯 플롯"을 만들려고합니다. 즉, 플롯의 왼쪽과 오른쪽에 다른 색상 표를 사용하고 싶습니다. 따라서 두 가지 색상 막대가 필요합니다. 불행히도 두 번째 색상 막대의 위치를 ​​직접 손으로 설정하고 레이블이나 제목이 포함될 때마다 수정해야합니다. 그걸 자동화 할 방법이 있을까요?matplotlib 플롯에서 두 번째 색상 막대의 정확한 크기를 얻는 방법은 무엇입니까?

다음 최소 예제의 rect 매개 변수를 올바른 색상 막대에서 추출 할 수 있는지 궁금합니다. 그것은 내가 조금만 옮겼을 때 도움이 될 것입니다. 다른 (더 나은) 아이디어도 환영합니다.

현재 레이블 또는 제목을 변경할 때마다 수동으로 설정된 왼쪽 색상 막대의 위치를 ​​다시 수정해야합니다. 이것은 매우 성가신 일입니다. 나는 실행 최소한의 예제를 포함하고는 출력이 생성됩니다

import matplotlib as mpl 
params = { 
      'xtick.direction' : 'out', 
      'ytick.direction' : 'out', 
      'text.usetex'  : True, 
     } 

mpl.rcParams.update(params) 
mpl.rcParams.update({'figure.autolayout': True}) 

import numpy as np 
import matplotlib.pyplot as plt 
import matplotlib.colors as colors 


extent_arr1 = [-1,0, -1,1] 
extent_arr2 = [ 0,1, -1,1] 
M = 501 

# define test-data 
data_arr1 = np.zeros((M, M)) 
data_arr2 = np.ones((M, M)) 

# define figure 
fig = plt.figure() 
ax = fig.add_subplot(111) 

# left plot: 
image1 = ax.imshow(data_arr1, cmap='jet', interpolation='bilinear', extent=extent_arr1, \ 
        origin='lower') 
plt.title("Minimal example") 
cbar1 = plt.colorbar(image1) 

# right plot: 
image2 = ax.imshow(data_arr2, cmap='gnuplot', interpolation='bilinear', extent=extent_arr2, \ 
        origin='lower') 

# define axes-labels: 
plt.xlabel(r"$x$") 
plt.ylabel(r"$y$") 

# define colour-bar at left side: 
rect_loc = [0.0, 0.08, 0.03, 0.88] # define position ---> how to automatise this? 
cax2 = fig.add_axes(rect_loc)  # left | bottom | width | height 
cbar2 = plt.colorbar(image2, cax=cax2) 
cbar2.ax.yaxis.set_ticks_position('left') 

# set limits: 
ax.set_xlim(-1,1) 
ax.set_ylim(-1,1) 

plt.show() 

출력 : enter image description here

사전에 감사!

답변

2

물론 색상 막대 축을 만들어 플롯 옆에 배치하는 방법은 여러 가지가 있습니다. 나는 그 질문을 읽는 것이 좋습니다 :

많은 두 번째 년 Colorbar로 확장 할 수 있습니다. 개인적으로 선호하는 솔루션은 축 분할자를 사용하는 다음과 같습니다. 장점은 색상 막대가 축의 크기를 유지한다는 것입니다.

import matplotlib.pyplot as plt 
from mpl_toolkits.axes_grid1 import make_axes_locatable 
import numpy as np; np.random.seed(1) 

plt.rcParams.update({'figure.autolayout': True}) 

fig, ax = plt.subplots(figsize=(6,4)) 
im = ax.imshow(np.random.rand(10,10), extent=[-1,0,0,1], cmap="RdYlGn") 
im2 = ax.imshow(np.random.rand(10,10), extent=[0,1,0,1], cmap="magma") 
ax.set_xlabel("x label") 
ax.set_ylabel("y label") 
ax.set_xlim(-1,1) 
ax.set_ylim(0,1) 

divider = make_axes_locatable(ax) 
cax = divider.new_horizontal(size="5%", pad=0.2) 
fig.add_axes(cax) 
fig.colorbar(im2, cax=cax) 

cax2 = divider.new_horizontal(size="5%", pad=0.7, pack_start=True) 
fig.add_axes(cax2) 
cb2 = fig.colorbar(im, cax=cax2) 
cb2.ax.yaxis.set_ticks_position('left') 
plt.show() 

enter image description here

관련 문제