[Python] Customize Colormap when drawing graphs with matplotlib

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.

Preparation

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()

plot_01.png

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()

plot_02.png

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. plot_03.png

Colormap customization

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()

plot_04.png

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()

plot_04-2.png

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()

plot_05.png

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()

plot_06.png

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()

plot_07.png

Code for this article

The code is posted on GitHub. https://github.com/matsuken92/Qiita_Contents/blob/master/General/Matplotlib_color_settings.ipynb

reference

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

[Python] Customize Colormap when drawing graphs with matplotlib
When matplotlib doesn't work with python2.7
[Python] How to draw multiple graphs with Matplotlib
Heatmap with Python + matplotlib
[Python] Ravel () is convenient when drawing multiple graphs
Real-time drawing with matplotlib
Drawing with Python Tinker
(For those unfamiliar with Matplotlib) Tips for drawing graphs with Seaborn
Graph drawing method with matplotlib
Error when playing with python
Animate multiple graphs with matplotlib
[python] How to use the library Matplotlib for drawing graphs
Create plot animation with Python + Matplotlib
A python graphing manual with Matplotlib.
Easy to draw graphs with matplotlib
Draw Lyapunov Fractal with Python, matplotlib
Lognormal probability plot with Python, matplotlib
Precautions when using six with Python 2.5
[Python] Format when to_csv with pandas
[Python] Set the graph range with matplotlib
Snippet when searching all bits with python
Note when creating an environment with python
Try drawing a normal distribution with matplotlib
[Python] Drawing a swirl pattern with turtle
Precautions when solving DP problems with Python
Write SVG graphs with matplotlib on heroku
Display Japanese graphs with VS Code + matplotlib
[Python] Let's make matplotlib compatible with Japanese
Drawing with Matrix-Reinventor of Python Image Processing-
Try drawing a map with python + cartopy 0.18.0
[Scientific / technical calculation by Python] Drawing animation of parabolic motion with locus, matplotlib
Error when installing a module with Python pip
[Python] limit axis of 3D graph with Matplotlib
Read Python csv data with Pandas ⇒ Graph with Matplotlib
Drawing tips with matplotlib on the server side
Getting Started with Drawing with matplotlib: Writing Simple Functions
Personal tips when doing various things with Python 3
Precautions when dealing with control structures in Python 2.6
A memo when creating a python environment with miniconda
Character encoding when dealing with files in Python 3
[python] [vscode] When you get angry with space-tab-mixed
Graph drawing with jupyter (ipython notebook) + matplotlib + vagrant
Materials to read when getting started with Python
[python] Streamline drawing
FizzBuzz with Python3
Scraping with Python
Statistics with python
Scraping with Python
Python with Go
#Python basics (#matplotlib)
Twilio with Python
Play with 2016-Python
Tested with Python
Animation with matplotlib
with syntax (Python)
My matplotlib (python)
Japanese with matplotlib
Bingo with python
Animation with matplotlib
Histogram with matplotlib
Animate with matplotlib