2017-04-19 54 views
2

這是爲了闡明問題標題。說你有一個整數的四個清單,與您要製作的散點圖:Matplotlib:添加孿生y軸而不使用其在繪圖中的值

a=[3,7,2,8,12,17] 
b=[9,4,11,7,6,3] 
c=[9,3,17,13,10,5] 
d=[5,1,1,14,5,8] 

也具有這樣的功能,爲簡單起見f(x)=1/x,適用於所有名單,從而使:

from __future__ import division 
a1=[1/i for i in a] 
b1=[1/i for i in b] 
c1=[1/i for i in c] 
d1=[1/i for i in d] 

我的問題:如何知道函數返回的值從0.061.0,,而不使用散點圖中的a1,b1,c1,d1列表中的任何一個,如何添加第二個y軸?

我在說的是:如果你用傳統的方式產生下面的散點圖,那麼你如何根據a1,b1,c1,d1的值添加第二個y軸,而沒有使用任何序列他們在情節本身?

import matplotlib.pyplot as plt 
plt.scatter(a,b,c='red',label='reds') 
plt.scatter(c,d,c='blue',label='blues') 
plt.legend(loc='best') 

這是不具有第二y軸的散射: enter image description here

這是相同的一個的製成的版本,包括到目前爲止討論的第二Y軸: enter image description here

注:這個問題不同於this,因爲我不想用不同的尺度進行繪圖。我只想添加第二個軸的相關值。

+0

的[添加相關的第一y軸的第二y軸(http://stackoverflow.com/可能的複製問題/ 43149703 /添加一個與第一個y軸相關的第一個y軸) – ImportanceOfBeingErnest

+0

如果要使用的函數是在圖片中顯示的右側的比例尺沒有意義1/x,這可以通過將值b1和d1繪製到該軸上來看出。 – ImportanceOfBeingErnest

+0

但我不想繪製任何a1,b1等系列。這個尺度只是爲了顯示其意義。此外,該功能只是一個簡單的例子。 – FaCoffee

回答

3

要確保在新中軸線的數字是在相應的位置,以它們的逆:

import matplotlib.pylab as plt 

a=[3,7,2,8,12,17] 
b=[9,4,11,7,6,3] 
c=[9,3,17,13,10,5] 
d=[5,1,1,14,5,8] 

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

ax.scatter(a,b,c='red',label='reds') 
ax.scatter(c,d,c='blue',label='blues') 
ax.legend(loc='best') 
ax.set_ylabel('Y') 
# make shared y axis 
axi = ax.twinx() 
# set limits for shared axis 
axi.set_ylim(ax.get_ylim()) 
# set ticks for shared axis 
inverse_ticks = [] 
label_format = '%.3f' 
for tick in ax.get_yticks(): 
    if tick != 0: 
     tick = 1/tick 
    inverse_ticks.append(label_format % (tick,)) 
axi.set_yticklabels(inverse_ticks) 
axi.set_ylabel('1/Y') 
fig.tight_layout() 
fig.show() 

enter image description here

你也可以做到這一點的X軸:

# make shared x axis 
xaxi = ax.twiny() 
# set limits for shared axis 
xaxi.set_xlim(ax.get_xlim()) 
# set ticks for shared axis 
inverse_ticks = [] 
label_format = '%.3f' 
for tick in ax.get_xticks(): 
    if tick != 0: 
     tick = 1/tick 
    inverse_ticks.append(label_format % (tick,)) 
xaxi.set_xticklabels(inverse_ticks) 
xaxi.set_xlabel('1/X') 

enter image description here

+0

你也可以利用這樣一個事實,即你已經在尋找'0'值並且只改變刻度標籤的字符串值來用'inf'標記或者你想要的任何東西。 – berna1111

1

只是讓共享Y軸,並設置所需的限制和蜱的新中軸線喜歡這裏:

import matplotlib.pylab as plt 
import numpy as np 

a=[3,7,2,8,12,17] 
b=[9,4,11,7,6,3] 
c=[9,3,17,13,10,5] 
d=[5,1,1,14,5,8] 

plt.scatter(a,b,c='red',label='reds') 
plt.scatter(c,d,c='blue',label='blues') 
plt.legend(loc='best') 
ax = plt.gca() 
# make shared y axis 
ax2 = ax.twinx() 
# set limits for shared axis 
ax2.set_ylim([0,1]) 
# set ticks for shared axis 
plt.yticks(np.arange(0.06, 1, 0.14)) 
plt.show() 

enter image description here

+1

這個解決方案顯然是不正確的。嘗試繪製倒排列表;點不會重疊! – ImportanceOfBeingErnest

相關問題