2016-09-26 145 views
0
import matplotlib.pyplot as plt 
x = [1,2,3,4,5,-6,7,8] 
y = [5,2,4,-2,1,4,5,2] 
plt.scatter(x,y, label='test', color='k', s=25, marker="o") 
plt.xlabel('x') 
plt.ylabel('y') 
plt.title('Test') 
plt.legend() 
plt.show() 
plt.legend() 
plt.show() 

當該值是負y變化我試圖改變顏色=「R」 和當x變化到負我試圖改變標記=「o」的值設定爲「 X」。我是matplotlib的新手。2D散點圖Matplotlib

作爲一個附加問題,如何影響x和y的顏色和標記,如-1到-5,.5到0,0到.5,.5到1的範圍。我需要兩種顏色的四個標記共8個變體。

回答

1

您可以使用numpy.where獲取y值爲正值或負值的指示,然後繪製相應的值。

import numpy as np 
import matplotlib.pyplot as plt 


x = np.array([1, 2, 3, 4, 5, -6, 7, 8, 2, 5, 7]) 
y = np.array([5, 2, 4, -2, 1, 4, 5, 2, -1, -5, -6]) 
ipos = np.where(y >= 0) 
ineg = np.where(y < 0) 
plt.scatter(x[ipos], y[ipos], label='Positive', color='b', s=25, marker="o") 
plt.scatter(x[ineg], y[ineg], label='Negative', color='r', s=25, marker="x") 
plt.xlabel('x') 
plt.ylabel('y') 
plt.title('Test') 
plt.legend() 
plt.show() 

編輯

您可以通過它們與& - 運算符(和運營商)分離爲

i_opt1 = np.where((y >= 0) & (0 < x) & (x < 3)) # filters out positive y-values, with x-values between 0 and 3 
i_opt2 = np.where((y < 0) & (3 < x) & (x < 6)) # filters out negative y-values, with x between 3 and 6 
plt.scatter(x[i_opt1], y[i_opt1], label='First set', color='b', s=25, marker="o") 
plt.scatter(x[i_opt2], y[i_opt2], label='Second set', color='r', s=25, marker="x") 

添加幾個條件的np.where執行相同的你所有的不同要求。

Example of multiple conditions

Link to documentation of np.where

+0

感謝您的代碼和我稍作修改它添加軸。但是我有一個附加問題,我得到另一個變量z,它必須映射到這個圖表上,並且它只對標記類型有說法。 -1

-1

這是Altair將是一件輕而易舉的情況。

import pandas as pd 

x = [1,2,3,4,5,-6,7,8] 
y = [5,2,4,-2,1,4,5,2] 

df = pd.DataFrame({'x':x, 'y':y}) 
df['cat_y'] = pd.cut(df['y'], bins=[-5, -1, 1, 5]) 
df['x>0'] = df['x']>0 
Chart(df).mark_point().encode(x='x',y='y',color='cat_y', shape='x>0').configure_cell(width=200, height=200) 

enter image description here