2

I am plotting a graph where my x variable is 'Mg' and my y variable is 'Si'. I have a third variable called 'binary'. If binary is equal to 0 or 1, how do I colour the plotted point in red or black respectively?

I need to use the functions plt.scatter and colourbar(). I've read about colourbar but it seems to generate a continuous spectrum of colour. I've tried using plt.colors.from_levels_and_colors instead but I'm not really sure how to use it properly.

levels = [0,1]
colors = ['r','b']
cmap, norm = plt.colors.from_levels_and_colors(levels, colors)
plt.scatter(data_train['Mg'], data_train['Si'], c = data_train['binary'])
plt.show()

Also, in the future, instead of asking a question like this in this forum what can I do to solve the problem on my own? I try to read the documentation online first but often find it hard to understand.

cs95
  • 379,657
  • 97
  • 704
  • 746

2 Answers2

3

np.where makes encoding binary values easy.

np.where([1, 0, 0, 1], 'yes', 'no')
# array(['yes', 'no', 'no', 'yes'], dtype='<U3')

colors = np.where(data_train['binary'], 'black', 'red')
plt.scatter(data_train['Mg'], data_train['Si'], c=colors)
cs95
  • 379,657
  • 97
  • 704
  • 746
  • Thank you for replying so quickly. So is it inappropriate to use colorbar in this case? –  Jan 15 '19 at 22:07
  • @Anya I don't think so. A colorbar is for hues and gradients. You just seem to want to specify two colors here. – cs95 Jan 15 '19 at 22:13
  • 1
    @Anya: Have a look at [this](https://stackoverflow.com/questions/9707676/defining-a-discrete-colormap-for-imshow-in-matplotlib) answer to create a binary color map – Sheldore Jan 15 '19 at 22:16
0

If you're working with multiple "quantitive" colors, not with colormap, you probably should change your c from binary to mpl-friedly format. I.e.

point_colors = [colors[binary] for binary in data_train['binary']]
plt.scatter(data_train['Mg'], data_train['Si'], c=point_colors)
Slam
  • 8,112
  • 1
  • 36
  • 44