2d散点图Matplotlib

时间:2016-09-26 12:03:44

标签: matplotlib

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时变为负值我试图改变color ='r' 当x的值变为负值时,我试图将marker =“o”改为“x”。我是matplotlib的新手。

作为一个问题的补充,如何影响x和y的颜色和标记落在-1到-.5,.5到0,0到.5,.5到1的范围内。我需要四个两种颜色的标记,共8种变化。

2 个答案:

答案 0 :(得分: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()

修改

您可以通过将np.where - 运算符(和 - 运算符)分隔为&来向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") 添加几个条件

<%=

为所有不同的要求做同样的事情。

Example of multiple conditions

Link to documentation of np.where

答案 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