2013-04-09 27 views
39

Tôi muốn tạo chú thích colorbar cho bản đồ nhiệt, sao cho nhãn nằm ở giữa mỗi màu riêng biệt. Hãy xem ví dụ dưới đây (borrowed from here)matplotlib: colorbars và nhãn văn bản của nó

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

#discrete color scheme 
cMap = ListedColormap(['white', 'green', 'blue','red']) 

#data 
np.random.seed(42) 
data = np.random.rand(4, 4) 
fig, ax = plt.subplots() 
heatmap = ax.pcolor(data, cmap=cMap) 

#legend 
cbar = plt.colorbar(heatmap) 
cbar.ax.set_yticklabels(['0','1','2','>3']) 
cbar.set_label('# of contacts', rotation=270) 

# put the major ticks at the middle of each cell 
ax.set_xticks(np.arange(data.shape[1]) + 0.5, minor=False) 
ax.set_yticks(np.arange(data.shape[0]) + 0.5, minor=False) 
ax.invert_yaxis() 

#lebels 
column_labels = list('ABCD') 
row_labels = list('WXYZ') 
ax.set_xticklabels(column_labels, minor=False) 
ax.set_yticklabels(row_labels, minor=False) 

plt.show() 

mà tạo ra cốt truyện sau: pmesh plot

Lý tưởng nhất là tôi muốn tạo ra một thanh huyền thoại trong đó có bốn màu sắc và đối với mỗi màu sắc, một nhãn trong trung tâm của nó: 0,1,2,3,> 4

Trả lời

51
import matplotlib.pyplot as plt 
import numpy as np 
from matplotlib.colors import ListedColormap 

#discrete color scheme 
cMap = ListedColormap(['white', 'green', 'blue','red']) 

#data 
np.random.seed(42) 
data = np.random.rand(4, 4) 
fig, ax = plt.subplots() 
heatmap = ax.pcolor(data, cmap=cMap) 

#legend 
cbar = plt.colorbar(heatmap) 

cbar.ax.get_yaxis().set_ticks([]) 
for j, lab in enumerate(['$0$','$1$','$2$','$>3$']): 
    cbar.ax.text(.5, (2 * j + 1)/8.0, lab, ha='center', va='center') 
cbar.ax.get_yaxis().labelpad = 15 
cbar.ax.set_ylabel('# of contacts', rotation=270) 


# put the major ticks at the middle of each cell 
ax.set_xticks(np.arange(data.shape[1]) + 0.5, minor=False) 
ax.set_yticks(np.arange(data.shape[0]) + 0.5, minor=False) 
ax.invert_yaxis() 

#lebels 
column_labels = list('ABCD') 
row_labels = list('WXYZ') 
ax.set_xticklabels(column_labels, minor=False) 
ax.set_yticklabels(row_labels, minor=False) 

plt.show() 

Bạn đã rất thân thiết. Khi bạn có tham chiếu đến trục thanh màu, bạn có thể làm những gì bạn muốn, bao gồm việc đặt nhãn văn bản ở giữa. Bạn có thể muốn chơi với định dạng để làm cho nó dễ nhìn hơn.

demo

+0

cảm ơn! rất nhiều đánh giá cao. – dimka

+0

Tôi đã thử điều này và nó gần như hoạt động. Đối với một số lý do tên nhãn trục "# số liên lạc" biến mất do "cbar.ax.axis ('off')" dòng. bất kỳ cách nào để giữ nhãn trên? – dimka

+0

@dimka xem chỉnh sửa, chỉ cần tắt các dấu khác nhau một chút. Bạn vẫn phải tinh chỉnh phông chữ để trông đẹp hơn, nhưng tôi để nó như một bài tập cho người đọc;) – tacaswell

Các vấn đề liên quan