2017-05-30 84 views
0

matplotlib: colorbars and its text labels借來的代碼如何將「cbar.ax.text」的字體更改爲Arial?

我正在研究類似的圖,但我無法弄清楚如何將「cbar.ax.text」的字體更改爲Arial。

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() 
+0

[如何更改matplotlib圖的字體大小]的可能的副本(https://stackoverflow.com/questions/3899980/how-to-change-the-font-size-on-a-matplotlib-plot ) – Luce

+0

@Luce我試過了,但它改變了除了cbar的標籤之外的所有東西的字體。 – user8087767

回答

0

我聯繫的問題是不完全相同的副本(哎呀),但給你如何編輯全局字體屬性的想法。添加以下行的代碼,你的頂部:

font = {'family' : 'sans-serif', 
     'sans-serif': 'Ariel'} 

matplotlib.rc('font', **font) 

見matplotlib的documentation這個問題:How to change the font size on a matplotlib plot

+0

它不會將字體從cbar更改爲Arial。它會更改軸,但不會更改顏色欄。 – user8087767

+0

如果刪除文本標籤周圍的$,它確實有效。即改變:'爲j,枚舉實驗(['$ 0 $','$ 1 $','$ 2 $','$> 3 $']):'爲'爲j,枚舉實驗(['0', '1', '2', '> 3']):' – Luce

相關問題