LoginSignup
HIKARITAKA
@HIKARITAKA

Are you sure you want to delete the question?

If your question is resolved, you may close it.

Leaving a resolved question undeleted may help others!

We hope you find it useful!

条件によって、散布図のプロットの色などの種類を変えたい_Python3

解決したいこと

1つの出力結果(x,y平均)をプロットする際に、条件によって、散布図(横軸:x、縦軸:yの平均値)のプロットの色などの種類を変えたいです。

例)
条件
1.x,yの3×3の配列データがそれぞれ3つ(x1~x3、y1~y3)
2.x1のデータに対応するy1~y3の各要素ごとの平均値をプロットする
3.ただし、y1~y3の各要素の最大/最小の値が10以上か未満で場合分け(プロットの色は、10未満:赤、10以上:緑)

条件を分岐して、プロットを色分けする部分の表現の仕方が分からず、方法を教えて下さい。

該当するソースコード

ソースコードを入力

例)

import numpy as np
import matplotlib.pyplot as plt

# x:3データ
x1 = np.array([[28, 63, 14],
              [77, 22, 40],
              [5, 47, 48]])

x2 = np.array([[47, 12, 4],
              [2, 34, 76],
              [88, 34, 12]])

x3 = np.array([[54, 13, 87],
              [84, 54, 6],
              [32, 2, 9]])

# y:3データ
y1 = np.array([[64, 5, 1],
              [3, 65, 98],
              [75, 2, 8]])

y2 = np.array([[45, 21, 54],
              [7, 32, 87],
              [32, 28, 65]])

y3 = np.array([[98, 62, 8],
              [29, 24, 74],
              [78, 31, 78]])

x_123 = [x1] + [x2] + [x3]
y_123 = [y1] + [y2] + [y3]

# xの1つ目のデータ
x_123_0 = x_123[0]
# yのy1~y3の各要素ごとの平均
y_123_avg_x0 = np.mean(y_123, axis=0)

# yの1~3の各要素の最大最小
y_123_max = np.max(y_123, axis=0)
y_123_min = np.min(y_123, axis=0) 

# 閾値10
y_pp10more = y_123_max / y_123_min

fig = plt.figure()
ax = fig.add_subplot(1,1,1)

# プロットの色を変えたい
##################################################
#各要素に対して、(最大/最小) <10のとき、
if y_pp10more < 10:
    ax.scatter(x_123_0, y_123_avg_x0, c='red')
#各要素に対して、最大/最小 >=10のとき、
else:
    ax.scatter(x_123_0, y_123_avg_x0, c='green')
##################################################

ax.set_title('scatter plot')
ax.set_xlabel('x')
ax.set_ylabel('y平均')

fig.show()
0

2Answer

@Ryuya-couchpotatoさん
ありがとうございます。
まさしくこの出力結果となるような書き方をしたかったです。
解説も丁寧にしていただき、ありがとうございます。
コードを書き始めたばかりだったので、どんな風に考えて書けばよいか、
勉強になりました。

0

解決案

color = []
for i in (y_pp10more < 10).reshape(-1):
    color.append('red' if i else 'green')
    # 下の式と同じ意味
    # if i is True:
    #     color.append('red')
    # else:
    #     color.append('green')

ax.scatter(x_123_0, y_123_avg_x0, c=color)

解説

if y_pp10more < 10:

はじめに、上の条件式は”y_pp10more < 10”の結果が3*3の配列で、True,Falseで判定できないためエラーになります。実際に"print(y_pp10more < 10)"をすると以下のようになります。

[[ True False False]
 [ True  True  True]
 [ True False  True]]

そのため解決案の2,3行目で、y_pp10more < 10の結果を1つずつ取り出し、それぞれに対して条件分岐するようにしました。

また、scatterはcに配列を渡せるので、1行目でcolorを宣言、2,3行目で判定結果に対応した色をcolorに追加し、この配列をscatterに渡しています。

0

Your answer might help someone💌