2011-09-26 110 views
32

我正在構建一個用於數據分析的小工具,我已經到了必須繪製準備好的數據的地步。之前的代碼生成以下兩個等長的列表。matplotlib字符串作爲x軸上的標籤

t11 = ['00', '01', '02', '03', '04', '05', '10', '11', '12', '13', '14', '15', '20', '21', '22', '23', '24', '25', '30', '31', '32', '33', '34', '35', '40', '41', '42', '43', '44', '45', '50', '51', '52', '53', '54', '55'] 

t12 = [173, 135, 141, 148, 140, 149, 152, 178, 135, 96, 109, 164, 137, 152, 172, 149, 93, 78, 116, 81, 149, 202, 172, 99, 134, 85, 104, 172, 177, 150, 130, 131, 111, 99, 143, 194] 

基於此,我想用matplotlib.plt.hist構建一個直方圖。但是,有幾個問題: 1. t11 [x]和t12 [x]連接到所有x。其中t11 [x]實際上是一個字符串。它代表一個特定的檢測器組合。例如:'01'表示檢測是在第一個檢測器的第0段和第2個檢測器的第1段進行的。我的目標是將t11中的每個條目都作爲x軸上的標記點。 t12條目將定義t11條目上方的條的高度(在對數y軸上)

如何配置這樣的x軸? 2.這對我來說都是非常新的。我在文檔中找不到任何相關內容。很可能是因爲我不知道要搜索什麼。 SO:我想要達到什麼樣的「官方」名稱?這也會幫助我很多。

回答

52

使用xticks命令。

import matplotlib.pyplot as plt 

t11 = ['00', '01', '02', '03', '04', '05', '10', '11', '12', '13', '14', '15', 
     '20', '21', '22', '23', '24', '25', '30', '31', '32', '33', '34', '35', 
     '40', '41', '42', '43', '44', '45', '50', '51', '52', '53', '54', '55'] 

t12 = [173, 135, 141, 148, 140, 149, 152, 178, 135, 96, 109, 164, 137, 152, 
     172, 149, 93, 78, 116, 81, 149, 202, 172, 99, 134, 85, 104, 172, 177, 
     150, 130, 131, 111, 99, 143, 194] 


plt.bar(range(len(t12)), t12, align='center') 
plt.xticks(range(len(t12)), t11, size='small') 
plt.show() 
+2

你爲什麼在兩行中都使用'len(t12)'?不應該是'len(t11)'? – User

3

在matplotlib術語中,您正在尋找設置自定義滴答的方法。

看來你不能用pyplot.hist快捷鍵實現這個。您需要逐步構建您的圖像。 Stack Overflow已經有了一個答案,這個問題與你的非常相似,應該讓你開始:Matplotlib - label each bin

11

對於matplotlib的面向對象的API可以繪製上axisx-ticks自定義文本與下面的代碼:

x = np.arange(2,10,2) 
y = x.copy() 
x_ticks_labels = ['jan','feb','mar','apr','may'] 

fig, ax = plt.subplots(1,1) 
ax.plot(x,y) 

# Set number of ticks for x-axis 
ax.set_xticks(x) 
# Set ticks labels for x-axis 
ax.set_xticklabels(x_ticks_labels, rotation='vertical', fontsize=18) 

enter image description here

0

首先,你需要訪問軸對象:

fig, ax = plt.subplots(1,1) 

then :

ax.set_yticks([x for x in range(-10,11)]) 
ax.set_yticklabels(['{0:2d}'.format(abs(x)) for x in range(-10, 11)])