5

Example code:

import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
xlist = [1, 2, 3, 4, 5]
ylist = [1, 5, 3, 4, 2]
zlist = [6, -3, 6, -1, 2]
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
ax.scatter(xlist, ylist, zlist)
plt.ticklabel_format(useOffset=False)   
plt.show()

A simple 3d scatter plot... let's say I want the minimum point (on the z axis) to be a different color. So that point be the second point: x = 2, y = 5, z = -3. What is the simplest way to achieve this? (note: if there is a tie for minimum, all minima should be highlighted)

My workaround is to use min to find the min in zlist, then say min_index = zlist.index(min(zlist)), then remove the entry (and save it) at min_index from xlist, ylist, and zlist. Then to plot that point individually with another ax.scatter command of just one point (the minimum). But that seems pretty inelegant, and it doesn't work for ties.

1 Answer 1

7

You could use NumPy to find the minimum value in zlist and generate a boolean array which is True where zlist equals zmin (note this could happen more than once). Then use np.where to generate an array which is red when mask is True and blue otherwise:

zmin = np.min(zlist)
mask = np.array(zlist) == zmin
color = np.where(mask, 'red', 'blue')

You cand then pass color=color to ax.scatter to create the desired scatter plot:

import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D

xlist = [1, 2, 3, 4, 5]
ylist = [1, 5, 3, 4, 2]
zlist = [6, -3, 6, -1, 2]
zmin = np.min(zlist)
mask = np.array(zlist) == zmin
color = np.where(mask, 'red', 'blue')
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
ax.scatter(xlist, ylist, zlist, color=color)
plt.ticklabel_format(useOffset=False)   
plt.show()

enter image description here

Sign up to request clarification or add additional context in comments.

2 Comments

Beat me by a few seconds. Very clever use of where. This is definitely the right solution with minimum waste. +1
Today I learned about "where"... numpy really has a function for anything, thanks

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.