色を決めるのが面倒くさいので自動で決めたい


色を決めるのが面倒くさいとき、ありますよね。そのとき用の小ネタです。matplotlib で何かプロットを作ります。


```python
%matplotlib inline
import matplotlib.pyplot as plt
import pandas as pd
```


```python
import numpy as np
from sklearn.datasets.samples_generator import make_blobs
n_labels = 3
X, label = make_blobs(n_samples=100, centers=n_labels, n_features=2, cluster_std=np.random.rand(n_labels)*3)
df = pd.DataFrame(dict(x1=X[:,0], x2=X[:,1], label=label))
```

色を決めるときは、たとえばこのようにします。


```python
colors = {0:'red', 1:'blue', 2:'green'}
```


```python
fig, ax = plt.subplots()
grouped = df.groupby('label')
for key, group in grouped:
    group.plot(ax=ax, kind='scatter', x='x1', y='x2', label=key, color=colors[key])
plt.legend(loc = 'right',
          bbox_to_anchor = (0.7, 0.5, 0.5, 0.1),
          borderaxespad = 0.0)
plt.grid()
plt.show()
```


![output_5_1.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/211162/9fe95856-6356-e86b-35aa-7ca2cf116365.png)



色の数が３つくらいなら、以上のようにすればいいんですが、色が１０個とかもっとあると面倒臭いじゃないですか。ならばランダムに決めてしまいましょう。


```python
import matplotlib
import random
colors = [cname for cname in matplotlib.colors.cnames.keys()]
random.shuffle(colors)
```

このようにすると、matplotlib で定義されている（名前のある）色が全列挙されます。（順番はランダムにシャッフルされています）


```python
colors
```




    ['darkkhaki',
     'black',
     'blue',
     'burlywood',
     'gainsboro',
     'mintcream',
     'lightslategray',
     'brown',
     'cyan',
     'mediumseagreen',
     'darkolivegreen',
     'darkmagenta',
     'lightblue',
     'mediumspringgreen',
     'slategrey',
     'mediumorchid',
     'navajowhite',
     'red',
     'plum',
     'mediumblue',
     'indianred',
     'hotpink',
     'darkorange',
     'coral',
     'teal',
     'sandybrown',
     'lavender',
     'khaki',
     'lightsalmon',
     'lightslategrey',
     'azure',
     'palegoldenrod',
     'aliceblue',
     'darkblue',
     'lightsteelblue',
     'chartreuse',
     'silver',
     'magenta',
     'yellowgreen',
     'crimson',
     'aqua',
     'linen',
     'lightyellow',
     'forestgreen',
     'grey',
     'darkorchid',
     'floralwhite',
     'lightgreen',
     'lime',
     'antiquewhite',
     'dimgrey',
     'ivory',
     'gray',
     'aquamarine',
     'darkgrey',
     'honeydew',
     'powderblue',
     'darkgreen',
     'lightgrey',
     'darkseagreen',
     'darkgray',
     'chocolate',
     'beige',
     'slateblue',
     'cadetblue',
     'seashell',
     'olive',
     'yellow',
     'salmon',
     'dodgerblue',
     'peru',
     'maroon',
     'wheat',
     'lightcyan',
     'peachpuff',
     'lightseagreen',
     'royalblue',
     'goldenrod',
     'paleturquoise',
     'purple',
     'indigo',
     'tan',
     'lightgoldenrodyellow',
     'lemonchiffon',
     'darkturquoise',
     'orange',
     'orchid',
     'lightskyblue',
     'saddlebrown',
     'lightgray',
     'darksalmon',
     'ghostwhite',
     'limegreen',
     'turquoise',
     'navy',
     'rosybrown',
     'moccasin',
     'papayawhip',
     'green',
     'greenyellow',
     'cornflowerblue',
     'darkcyan',
     'blanchedalmond',
     'deepskyblue',
     'darkslateblue',
     'midnightblue',
     'snow',
     'lightpink',
     'darkslategrey',
     'whitesmoke',
     'oldlace',
     'pink',
     'mediumvioletred',
     'mistyrose',
     'sienna',
     'blueviolet',
     'fuchsia',
     'tomato',
     'dimgray',
     'palevioletred',
     'mediumpurple',
     'rebeccapurple',
     'lavenderblush',
     'thistle',
     'firebrick',
     'springgreen',
     'slategray',
     'violet',
     'skyblue',
     'darkgoldenrod',
     'darkviolet',
     'deeppink',
     'darkslategray',
     'mediumturquoise',
     'cornsilk',
     'mediumaquamarine',
     'steelblue',
     'lightcoral',
     'bisque',
     'olivedrab',
     'darkred',
     'gold',
     'white',
     'palegreen',
     'mediumslateblue',
     'seagreen',
     'lawngreen',
     'orangered']



そうすれば、色の数が数十個に増えても怖くありません。


```python
import numpy as np
from sklearn.datasets.samples_generator import make_blobs
n_labels = 10
X, label = make_blobs(n_samples=100, centers=n_labels, n_features=2, cluster_std=np.random.rand(n_labels)*3)
df = pd.DataFrame(dict(x1=X[:,0], x2=X[:,1], label=label))
```


```python
fig, ax = plt.subplots()
grouped = df.groupby('label')
for key, group in grouped:
    group.plot(ax=ax, kind='scatter', x='x1', y='x2', label=key, color=colors[key])
plt.legend(loc = 'right',
          bbox_to_anchor = (0.7, 0.5, 0.5, 0.1),
          borderaxespad = 0.0)
plt.grid()
plt.show()
```


![output_12_0.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/211162/4c9b7cd8-4465-c1c0-0ed5-a1714c3c2dca.png)



色合いが気に入らなければ、


```python
random.shuffle(colors)
```

で色を並び替えて、納得いくまで繰り返せばいいです。気に入った配色になれば、colors の中身を確認してそれを再利用すればいいです。


```python
fig, ax = plt.subplots()
grouped = df.groupby('label')
for key, group in grouped:
    group.plot(ax=ax, kind='scatter', x='x1', y='x2', label=key, color=colors[key])
plt.legend(loc = 'right',
          bbox_to_anchor = (0.7, 0.5, 0.5, 0.1),
          borderaxespad = 0.0)
plt.grid()
plt.show()
```


![output_16_0.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/211162/f4615361-f1e5-0bf9-09ae-7893a94d09f5.png)

# サンプルコード

色を自動で決めるコードを追記しました。

```Python
# coding: utf-8

# In[1]:


import random

import matplotlib
import matplotlib.pyplot as plt

edge_colors = ["brown", "black", "red", "blue", "green"]
looks = [
    [cname, 0, edge_colors[i % len(edge_colors)], i]
    for i, cname in enumerate(matplotlib.colors.cnames.keys())
]
random.shuffle(looks)

get_ipython().run_line_magic("matplotlib", "inline")

plt.figure(figsize=(10, 10), dpi=200)

index = 0
X = [random.random() for x in range(10000)]
Y = [random.random() for x in range(10000)]
plt.scatter(
    X,
    Y,
    c=looks[index][0],
    linewidths=looks[index][1],
    edgecolors=looks[index][2],
    alpha=0.5,
    label="data1",
)

index = 1
X = [random.random() for x in range(500)]
Y = [random.random() for x in range(500)]
plt.scatter(
    X, Y, c=looks[index][0], linewidths=2, edgecolors="black", alpha=0.5, label="data2"
)

index = 2
X = [random.random() for x in range(100)]
Y = [random.random() for x in range(100)]
plt.scatter(
    X, Y, c=looks[index][0], linewidths=2, edgecolors="red", alpha=0.5, label="data3"
)

index = 3
X = [random.random() for x in range(100)]
Y = [random.random() for x in range(100)]
plt.scatter(
    X, Y, c=looks[index][0], linewidths=2, edgecolors="blue", alpha=0.5, label="data4"
)

index = 4
X = [random.random() for x in range(100)]
Y = [random.random() for x in range(100)]
plt.scatter(
    X, Y, c=looks[index][0], linewidths=2, edgecolors="green", alpha=0.5, label="data5"
)

plt.legend()
plt.grid()
plt.show()

looks
```

![test-color.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/211162/b906a561-be54-3023-aa3d-d8a580914384.png)


```
[['palegoldenrod', 0, 'blue', 108],
 ['red', 0, 'brown', 120],
 ['coral', 0, 'black', 16],
 ['greenyellow', 0, 'brown', 55],
 ['cyan', 0, 'brown', 20],
 ['mediumseagreen', 0, 'black', 91],
 ['hotpink', 0, 'blue', 58],
 ['khaki', 0, 'red', 62],
 ['green', 0, 'green', 54],
 ['mediumslateblue', 0, 'red', 92],
 ['olive', 0, 'blue', 103],
 ['darkgray', 0, 'green', 24],
 ['thistle', 0, 'green', 139],
 ['moccasin', 0, 'green', 99],
 ['indigo', 0, 'brown', 60],
 ['darkslategrey', 0, 'red', 37],
 ['lightslategrey', 0, 'green', 79],
 ['darkslateblue', 0, 'brown', 35],
 ['firebrick', 0, 'brown', 45],
 ['chartreuse', 0, 'green', 14],
 ['mediumblue', 0, 'blue', 88],
 ['maroon', 0, 'black', 86],
 ['lightseagreen', 0, 'black', 76],
 ['goldenrod', 0, 'red', 52],
 ['cadetblue', 0, 'blue', 13],
 ['orchid', 0, 'red', 107],
 ['mediumpurple', 0, 'brown', 90],
 ['bisque', 0, 'black', 6],
 ['lightgoldenrodyellow', 0, 'brown', 70],
 ['navajowhite', 0, 'brown', 100],
 ['lightsalmon', 0, 'brown', 75],
 ['yellow', 0, 'black', 146],
 ['dimgray', 0, 'red', 42],
 ['rosybrown', 0, 'black', 121],
 ['tan', 0, 'red', 137],
 ['honeydew', 0, 'red', 57],
 ['salmon', 0, 'green', 124],
 ['darkblue', 0, 'black', 21],
 ['orangered', 0, 'black', 106],
 ['navy', 0, 'black', 101],
 ['papayawhip', 0, 'red', 112],
 ['darkorchid', 0, 'black', 31],
 ['lightblue', 0, 'red', 67],
 ['blueviolet', 0, 'brown', 10],
 ['lightsteelblue', 0, 'brown', 80],
 ['cornflowerblue', 0, 'red', 17],
 ['powderblue', 0, 'red', 117],
 ['magenta', 0, 'brown', 85],
 ['seagreen', 0, 'black', 126],
 ['royalblue', 0, 'red', 122],
 ['floralwhite', 0, 'black', 46],
 ['antiquewhite', 0, 'black', 1],
 ['lightslategray', 0, 'blue', 78],
 ['darkslategray', 0, 'black', 36],
 ['violet', 0, 'red', 142],
 ['midnightblue', 0, 'black', 96],
 ['orange', 0, 'brown', 105],
 ['skyblue', 0, 'brown', 130],
 ['deeppink', 0, 'brown', 40],
 ['olivedrab', 0, 'green', 104],
 ['turquoise', 0, 'black', 141],
 ['lightyellow', 0, 'black', 81],
 ['steelblue', 0, 'black', 136],
 ['lavenderblush', 0, 'green', 64],
 ['slateblue', 0, 'black', 131],
 ['dodgerblue', 0, 'green', 44],
 ['beige', 0, 'brown', 5],
 ['darkred', 0, 'red', 32],
 ['snow', 0, 'green', 134],
 ['darkgreen', 0, 'brown', 25],
 ['aliceblue', 0, 'brown', 0],
 ['ivory', 0, 'black', 61],
 ['mediumorchid', 0, 'green', 89],
 ['mediumaquamarine', 0, 'red', 87],
 ['plum', 0, 'black', 116],
 ['rebeccapurple', 0, 'green', 119],
 ['darkolivegreen', 0, 'green', 29],
 ['brown', 0, 'black', 11],
 ['lightcyan', 0, 'green', 69],
 ['sienna', 0, 'blue', 128],
 ['ghostwhite', 0, 'brown', 50],
 ['blue', 0, 'green', 9],
 ['teal', 0, 'blue', 138],
 ['lightgreen', 0, 'red', 72],
 ['tomato', 0, 'brown', 140],
 ['chocolate', 0, 'brown', 15],
 ['lightgrey', 0, 'blue', 73],
 ['deepskyblue', 0, 'black', 41],
 ['mediumspringgreen', 0, 'blue', 93],
 ['mintcream', 0, 'red', 97],
 ['crimson', 0, 'green', 19],
 ['palegreen', 0, 'green', 109],
 ['azure', 0, 'green', 4],
 ['darkgoldenrod', 0, 'blue', 23],
 ['dimgrey', 0, 'blue', 43],
 ['darkcyan', 0, 'red', 22],
 ['darkmagenta', 0, 'blue', 28],
 ['peru', 0, 'green', 114],
 ['paleturquoise', 0, 'brown', 110],
 ['lightskyblue', 0, 'red', 77],
 ['seashell', 0, 'red', 127],
 ['lime', 0, 'red', 82],
 ['cornsilk', 0, 'blue', 18],
 ['springgreen', 0, 'brown', 135],
 ['white', 0, 'green', 144],
 ['lightgray', 0, 'black', 71],
 ['gray', 0, 'blue', 53],
 ['grey', 0, 'black', 56],
 ['mediumvioletred', 0, 'brown', 95],
 ['lavender', 0, 'blue', 63],
 ['aqua', 0, 'red', 2],
 ['darkviolet', 0, 'green', 39],
 ['lightpink', 0, 'green', 74],
 ['lightcoral', 0, 'blue', 68],
 ['silver', 0, 'green', 129],
 ['gainsboro', 0, 'green', 49],
 ['saddlebrown', 0, 'blue', 123],
 ['darkorange', 0, 'brown', 30],
 ['forestgreen', 0, 'red', 47],
 ['purple', 0, 'blue', 118],
 ['peachpuff', 0, 'blue', 113],
 ['slategrey', 0, 'blue', 133],
 ['whitesmoke', 0, 'brown', 145],
 ['darkturquoise', 0, 'blue', 38],
 ['palevioletred', 0, 'black', 111],
 ['darkgrey', 0, 'black', 26],
 ['darkseagreen', 0, 'green', 34],
 ['lemonchiffon', 0, 'black', 66],
 ['fuchsia', 0, 'blue', 48],
 ['sandybrown', 0, 'brown', 125],
 ['indianred', 0, 'green', 59],
 ['pink', 0, 'brown', 115],
 ['aquamarine', 0, 'blue', 3],
 ['mistyrose', 0, 'blue', 98],
 ['mediumturquoise', 0, 'green', 94],
 ['yellowgreen', 0, 'red', 147],
 ['darkkhaki', 0, 'red', 27],
 ['oldlace', 0, 'red', 102],
 ['gold', 0, 'black', 51],
 ['black', 0, 'red', 7],
 ['lawngreen', 0, 'brown', 65],
 ['darksalmon', 0, 'blue', 33],
 ['linen', 0, 'green', 84],
 ['burlywood', 0, 'red', 12],
 ['limegreen', 0, 'blue', 83],
 ['blanchedalmond', 0, 'blue', 8],
 ['slategray', 0, 'red', 132],
 ['wheat', 0, 'blue', 143]]
```