8
7

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

matplotlibで色をグラデーションにする

Last updated at Posted at 2019-10-17

等間隔のグラデーションを作る

import matplotlib.pyplot as plt

# test data
x=[2,3,5,7,11,13,17]
y=[0,0,1,1,2,2,3]

# グラデーションを作る
cm=plt.get_cmap('Blues')  # 他にも'jet'など
cm_interval=[ i / (len(x) - 1) for i in range(len(x)) ]
cm=cm(cm_interval)

# plot
ax=plt.figure(figsize=(3, 3)).add_subplot(111)
ax.scatter(x=x, y=y, c=cm)
plt.savefig('prime_num.pdf')

for構文を使うとき: 色は2D-arrayで指定

import matplotlib.pyplot as plt

# test data
x=[2,3,5,7,11,13,17]
y=[0,0,1,1,2,2,3]

# グラデーションを作る
cm=plt.get_cmap('Blues')
cm_interval=[ i / (len(x) - 1) for i in range(len(x)) ]
cm=cm(cm_interval)

# plot
ax=plt.figure(figsize=(3, 3)).add_subplot(111)
for x_val, y_val, col in zip(x, y, cm):
    ax.scatter(x=x_val, y=y_val, c=[col]) # 色は2D-arrayで指定
plt.savefig('prime_num.pdf')

prime_num.jpg

数値に応じたグラデーションを作る

import matplotlib.pyplot as plt

# test data
x=[2,3,5,7,11,13,17]
y=[0,0,1,1,2,2,3]

# plot
ax=plt.figure(figsize=(3, 3)).add_subplot(111)
ax.scatter(x=x, y=y, c=y, cmap='Blues')  # ここで指定
plt.savefig('prime_num.pdf')

prime_num.jpg

注意点

'Blues'などの白色を含むcmapを使用すると、始めの値が白になるので、見えなくなる。'jet'を用いると問題はない。データの可視化の際には注意。

図1.jpg

↓ 'Blues'を用いるときの白色回避方法:

import matplotlib.pyplot as plt

# test data
x=[2,3,5,7,11,13,17]
y=[0,0,1,1,2,2,3]

# グラデーションを作る
cm=plt.get_cmap('Blues') 
cm_interval=[ i / (len(x)) for i in range(1, len(x)+1) ]  ## ここを変える !!!!!!
cm=cm(cm_interval)

# plot
ax=plt.figure(figsize=(3, 3)).add_subplot(111)
ax.scatter(x=x, y=y, c=cm)
plt.savefig('prime_num.pdf')

prime_num_blues.jpg

環境

Ubuntu 18.04
Python 3.7.3
matplotlib 3.1.0

8
7
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
8
7

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?