Saturday, March 16, 2019

legend and color in matplotlib's scatter plot



As in the example you mentioned, call plt.scatter for each group:
import numpy as np
from matplotlib import pyplot as plt

scatter_x = np.array([1,2,3,4,5])
scatter_y = np.array([5,4,3,2,1])
group = np.array([1,3,2,1,3])
cdict = {1: 'red', 2: 'blue', 3: 'green'}

fig, ax = plt.subplots()
for g in np.unique(group):
    ix = np.where(group == g)
    ax.scatter(scatter_x[ix], scatter_y[ix], c = cdict[g], label = g, s = 100)
ax.legend()
plt.show()
(from https://stackoverflow.com/questions/47006268/matplotlib-scatter-plot-with-color-label-and-legend-specified-by-c-option)

I got stuck
A solution was found in SO(https://stackoverflow.com/questions/3551242/numpy-index-slice-without-losing-dimension-information):

X[[10],:]
or
I = array([10])
X[I,:]
The dimensionality of an array is preserved when indexing is performed by a list (or an array) of indexes. This is nice because it leaves you with the choice between keeping the dimension and squeezing.

  • This did what I wanted: to generate arbitrary number of colors automatically.

https://stackoverflow.com/questions/12236566/setting-different-color-for-each-series-in-scatter-plot-on-matplotlib

No comments:

Post a Comment

Writing a post in Markdown in Blogger

Following articles are helpful. * [【令和最新版】Blogger で Markdown を用いて記事を書く方法](https://qiita.com/hoge_fu-ga/items/267ea5ad4f8c120eaeb8) * [Bl...