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()

When the value is y changes to negative i am trying to change color='r' and when the value of x change to negative i am trying to change marker="o" to "x". I am new to matplotlib.

As a add on question, how to affect color and marker for x and y falling in ranges like -1 to -.5, .5 to 0, 0 to .5, .5 to 1. I am need of four markers in two colors amounting to 8 variations.

Programmer_nltk
  • 863
  • 16
  • 38

2 Answers2

1

You can use numpy.where to get the indicies where the y-values are positive or negative and then plot the corresponding values.

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()

Edit

You can add several conditions to the np.where by separating them with the &-operator (and-operator) as

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")

Do the same for all of your different requirements.

Example of multiple conditions

Link to documentation of np.where

Community
  • 1
  • 1
pathoren
  • 1,634
  • 2
  • 14
  • 22
  • Thanks for the code and i slightly amended it adding axes. But I have a add on question, I got another variable z that has to be mapped on to this chart and it has a say only on the type of marker. -1 < Z <-.5 marker 0, -.5 < z < 0 marker x ,z between 0 to .5 marker ^ z between .5 to 1 marker .v. Is it possible to accommodate it in this code. – Programmer_nltk Sep 26 '16 at 13:19
-2

This is a case where Altair would be a breeze.

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

Nipun Batra
  • 11,007
  • 11
  • 52
  • 77