Python Advent Calendar 2015 from Adventar This is the article on the 21st day.
When drawing a graph in Python, I think you will use Matplotlib. Recently, there is a library called Seaborn that cleans the graph, and I love it. However, it is convenient to customize the Colormap with + α when you want to select or set the color more freely. This time I will introduce this.
First of all, it is the usual set import. Most of them are in Anaconda, but if you don't have them, you can install them with pip install <library name you want to install>
.
import numpy as np
import pandas as pd
from sklearn import datasets
import matplotlib.pyplot as plt
import matplotlib.cm as cm
%matplotlib inline
import seaborn as sns
sns.set(style="darkgrid", palette="muted", color_codes=True)
I use the usual iris dataset as a trial.
#Loading iris data
iris = datasets.load_iris()
If you obediently draw a scatter plot by color-coding each type of iris, it will be black and white like this ...
#Display of scatter plot (color becomes black and white ...)
plt.figure(figsize=(10,7))
plt.scatter(iris.data[:,0], iris.data[:,1], linewidths=0, alpha=1,
c=iris.target # iris.target represents the type[0, 1, 2]Because it contains, it is color-coded
)
plt.show()
You can specify the color by specifying the color name individually in the argument c
. But I don't think it's smart.
#Display scatter plot (specify colors one by one)
def set_color(l):
if l == 0:
return "b" # blue
elif l == 1:
return "g" # green
else:
return "r" # red
color_list = map(set_color, iris.target)
plt.figure(figsize=(10,7))
plt.scatter(iris.data[:,0], iris.data[:,1], linewidths=0, alpha=1,
c=iris.target # iris.target represents the type[0, 1, 2]Because it contains, it is color-coded
)
plt.show()
Since it is difficult to specify the color for each type, you can also use the color map originally defined in Matplotlib. For colormaps, you can see various colormap definitions by referring to here.
#Apply the defined color map
#Reference: http://matplotlib.org/examples/color/colormaps_reference.html
fig = plt.figure(figsize=(13,7))
im = plt.scatter(iris.data[:,0], iris.data[:,1], c=iris.target, linewidths=0, alpha=1,
cmap=cm.Accent #Specify the color map here
)
fig.colorbar(im)
plt.show()
But it's difficult to match the color you want.
So, let's customize and define this color map by ourselves. If you specify a color name or hexadecimal color code in the list, it will create a color map while smoothly linearly interpolating between them. I can't explain it well in Japanese, so let's take a look at a usage example.
#Customize colormap
from matplotlib.colors import LinearSegmentedColormap
def generate_cmap(colors):
"""Returns a self-defined color map"""
values = range(len(colors))
vmax = np.ceil(np.max(values))
color_list = []
for v, c in zip(values, colors):
color_list.append( ( v/ vmax, c) )
return LinearSegmentedColormap.from_list('custom_cmap', color_list)
Since there are 3 types of iris data, specify 3 colors. You can see a list of available color names by referring to here.
#Customize colors,Part 1:Specified by color name
#Reference: http://matplotlib.org/examples/color/named_colors.html
unique_value = set(iris.target)
print unique_value
# --> [0, 1, 2]
cm = generate_cmap(['mediumblue', 'limegreen', 'orangered'])
fig = plt.figure(figsize=(13,7))
im = plt.scatter(iris.data[:,0], iris.data[:,1], c=iris.target, linewidths=0, alpha=.8, cmap=cm)
fig.colorbar(im)
plt.show()
You can also specify it in hexadecimal notation instead of the color name. Here was helpful for the hexadecimal color code.
#Customize colors,Part 2: Specified in hexadecimal
# http://www5.plala.or.jp/vaio0630/hp/c_code.htm
cm = generate_cmap(['#87CEEB', '#2E8B57', '#F4A460'])
fig = plt.figure(figsize=(13,7))
im = plt.scatter(iris.data[:,0], iris.data[:,1], c=iris.target, linewidths=0, alpha=.8, cmap=cm)
fig.colorbar(im)
plt.show()
When a light color is specified, a white background is easier to see than a gray background. You can change it with seaborn, so let's make the background white.
#Customize colors,Part 3: Whiten the background
sns.set(style="whitegrid", palette="muted", color_codes=True)
cm = generate_cmap(['#87CEEB', '#2E8B57', '#F4A460'])
fig = plt.figure(figsize=(13,7))
im = plt.scatter(iris.data[:,0], iris.data[:,1], c=iris.target, linewidths=0, alpha=.8, cmap=cm)
fig.colorbar(im)
plt.show()
Next, let's express the value of the function that takes plane coordinates (two variables) as arguments in color. Color map customization is very effective in these cases.
#Smooth fill
n = 501
X, Y = np.meshgrid(np.linspace(0, 1, n), np.linspace(0, 1, n))
Z = np.sin(X*30) + np.cos(Y*30)
print np.min(Z), np.max(Z)
cm = generate_cmap(['#00008B', '#aaaaab', '#FFFFFF', '#F4D793', '#F4A460'])
fig =plt.figure(figsize=(10,8))
im = plt.pcolor(X, Y, Z, cmap=cm)
fig.colorbar(im)
plt.xlim(0, 1)
plt.ylim(0, 1)
plt.show()
Finally, here is an example of expressing the height of contour lines in color. It is also very effective to be able to specify the gradation included in the color map.
#contour
n = 201
X, Y = np.meshgrid(np.linspace(0, 1, n), np.linspace(0, 1, n))
Z = np.sin(X*20) * np.cos(Y*20)
cm = generate_cmap(['indigo', 'white', 'salmon'])
fig =plt.figure(figsize=(10,8))
interval = [i/10. -1 for i in range(20)]
im = plt.contour(X, Y, Z, interval, alpha=0.5, cmap=cm)
fig.colorbar(im)
plt.xlim(0, 1)
plt.ylim(0, 1)
plt.show()
The code is posted on GitHub. https://github.com/matsuken92/Qiita_Contents/blob/master/General/Matplotlib_color_settings.ipynb
Matplotlib colormaps reference http://matplotlib.org/examples/color/colormaps_reference.html Making a custom colormap using matplotlib in python (stackoverflow) http://stackoverflow.com/questions/24997926/making-a-custom-colormap-using-matplotlib-in-python List of colors with defined names http://matplotlib.org/examples/color/named_colors.html Hexadecimal color code http://www5.plala.or.jp/vaio0630/hp/c_code.htm
Recommended Posts