2016-09-26 113 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