2015-10-30 67 views
1

的用戶定義的列表我有繪製使用pyplot圖形的量的函數。代碼在這裏:添加二次X軸座標

def plot_results(results, expers): 
    """ 
    type results: list[list[float]] 
    type expers: list[int] 
    """ 
    label_builder = lambda index: 'experiment ' + str(index + 1) 
    colors = ('green', 'blue') 
    x_indices = list(map(compute_filesize, list(range(np.shape(results)[1])))) 
    x_percents = list(map(compute_percent, list(range(np.shape(results)[1])))) 

    fig, ax1 = plt.subplots() 
    for i in range(expers): 
     ax1.plot(x_indices, results[i], color=colors[i], lw=2, label=label_builder(i)) 
    ax1.legend() 
    plt.show() 

對於expers的每個值列出我的函數繪製圖表。 例如,if len(results) == len (expers) == 2,我會得到這樣的曲線圖:enter image description here

我需要創建二次X軸(類似於this,但它可以是X軸並且將位於圖的頂部)。 另一個區別是,我需要設置座標手動(例如ax2.set_coords(x_percents))的列表。

我使用ax2 = ax1.twinx()創造了新的軸。然後,我使用ax2.set_xticks(x_percents)建立座標列表。

但因爲每個x_percents[i] < x_indices[i]的,我得到了這樣的畫面:

enter image description here

(你可以看到,新的軸的所有的座標都位於左下角)

哪有我改變我的功能,使新的X軸:

  • 位於圖的頂側,

  • 都有自己的刻度,即x_percents每一值對應於分散在整個間隔的results[i]x_percents值?

+0

你想其實這個其他軸上繪製數據,或者這是第二軸第一的另一種represantation? – MaxNoe

+1

也'np.arange(results.shape [1])'會比更清潔和更快什麼喲正在做 – MaxNoe

回答

1

你的代碼表明,x_indicesx_percents是線性相關的。爲了使事情變得清晰,對他人有用的,我會承擔這2個變量如下:你可以實現創建涉及同一數據,這些雙軸線

x_indices = [0, 5, 10, 25, 50] 
max_size = max(x_indices) 
x_percents = [ n/max_size * 100 for n in x_indices] 

的一種方式,但只是有不同的標籤是這樣這樣的:先創建一個軸,然後再創建一個超過是(可以使用twinx/twiny的方法,但並非絕對必要,我會在這裏把它們用於方便和解釋導致你設置xticks的一個重要問題你的第一個軸)。然後,確保兩個x軸的範圍是相同的,設置的位置x-蜱相同如在第一軸和最後更改標籤:

import matplotlib.pyplot as plt 

vals = [1, 100, 14, 76, 33] # random data, aligned to `x_indices` 
fig, ax1 = plt.subplots(1,1) 
ax1.plot(x_indices, vals) 
ax2 = ax1.twiny() # Remark: twiny will create a new axes 
       # where the y-axis is shared with ax1, 
       # but the x-axis is independant - important! 
ax2.set_xlim(ax1.get_xlim()) # ensure the independant x-axes now span the same range 
ax2.set_xticks(x_indices) # copy over the locations of the x-ticks from the first axes 
ax2.set_xticklabels(x_percents) # But give them a different meaning 

simple example of adding two related axes to one graph

像這樣的曲線圖在物理學中經常遇到,例如波長和能量成反比。在一個座標軸上,您將能夠讀取一個刻度(例如納米)中的單位,而另一個將以不同的刻度(例如電子伏)表示相同的數據。