質問をすることでしか得られない、回答やアドバイスがある。

15分調べてもわからないことは、質問しよう!

新規登録して質問してみよう
ただいま回答率
85.48%
Matplotlib

MatplotlibはPythonのおよび、NumPy用のグラフ描画ライブラリです。多くの場合、IPythonと連携して使われます。

Python

Pythonは、コードの読みやすさが特徴的なプログラミング言語の1つです。 強い型付け、動的型付けに対応しており、後方互換性がないバージョン2系とバージョン3系が使用されています。 商用製品の開発にも無料で使用でき、OSだけでなく仮想環境にも対応。Unicodeによる文字列操作をサポートしているため、日本語処理も標準で可能です。

Q&A

解決済

1回答

522閲覧

matplotlibのanimationに色付けで生じたエラーの対処方法

IT_takumin

総合スコア8

Matplotlib

MatplotlibはPythonのおよび、NumPy用のグラフ描画ライブラリです。多くの場合、IPythonと連携して使われます。

Python

Pythonは、コードの読みやすさが特徴的なプログラミング言語の1つです。 強い型付け、動的型付けに対応しており、後方互換性がないバージョン2系とバージョン3系が使用されています。 商用製品の開発にも無料で使用でき、OSだけでなく仮想環境にも対応。Unicodeによる文字列操作をサポートしているため、日本語処理も標準で可能です。

0グッド

0クリップ

投稿2022/11/15 14:34

前提

エージェントベースモデルでシミュレーションを行なっていて、その結果をmatplotlibのアニメーションで視覚化したいのですが、エラーが出てその対処方法が分からず詰まってしまっています。

実現したいこと

''' im=ax.scatter(*plot_data,"o",ms=5,c=plot_color) ''' で下記の様なエラーが出てしまっているみたいなのですが、調べても何が問題なのかがわからず、対処方法が分からなかったので教えて頂けないでしょうか。

発生している問題・エラーメッセージ

TypeError Traceback (most recent call last) <ipython-input-19-0be488056fd3> in <module> 10 B.simulation() 11 plot_data,plot_color = B.positions() ---> 12 im=ax.scatter(*plot_data,"o",ms=5,c=plot_color) 13 ims.append(im) 14 #print(plot_data) 4 frames /usr/local/lib/python3.7/dist-packages/matplotlib/collections.py in set_sizes(self, sizes, dpi) 883 self._sizes = np.asarray(sizes) 884 self._transforms = np.zeros((len(self._sizes), 3, 3)) --> 885 scale = np.sqrt(self._sizes) * dpi / 72.0 * self._factor 886 self._transforms[:, 0, 0] = scale 887 self._transforms[:, 1, 1] = scale TypeError: ufunc 'sqrt' not supported for the input types, and the inputs could not be safely coerced to any supported types according to the casting rule ''safe''

該当のソースコード

python

1 2import numpy as np 3import matplotlib.pyplot as plt 4import matplotlib.animation as animation 5from IPython.display import HTML 6 7a1 = -0.034298 8b1 = 3.348394 9c1 = 4.252840 10d1 = -0.003423 11 12class Agent: 13 def __init__(self, name = None, pos = None, vel = None, SIZE = 10, VEL = 1, 14 RANGE_SEPARATE = 0.5,color = None): 15 self.name = name 16 self.pos = pos if pos else np.random.uniform(-SIZE, SIZE, 2) 17 self.vel = vel if vel else np.random.uniform(-VEL, VEL, 2) 18 self.SIZE = SIZE 19 self.VEL = VEL 20 self.RANGE_SEPARATE = RANGE_SEPARATE#分離範囲 21 self.vel_tmp = np.zeros(2)#移動 22 self.color = color if color else 'k' 23 24 25 def distance(self, other):#ユークリッド距離 26 return np.linalg.norm(self.pos - other.pos) 27 28 def ruleSeparate(self, others, ratio = 1): 29 others = [other for other in others if self.distance(other) < self.RANGE_SEPARATE]#範囲内に入ったエージェントの選別 30 v = np.zeros(2) 31 if not others: 32 return 0 33 for other in others: 34 d = self.pos - other.pos#dが-になる時ある? 35 v += d / self.distance(other)#進行方向の単位ベクトル 36 self.vel_tmp += v / len(others) * ratio#平均を出してそれをratio倍する 37 return v / len(others) * ratio 38 39 40 41 def calculate(self, others): 42 self.ruleSeparate(others, 0.5) 43 44 def update(self) -> bool:#返り値の型名 45 self.vel += self.vel_tmp#進行速度ベクトル更新 46 v = np.linalg.norm(self.vel) 47 #壁に当たったら反転 48 if (abs(self.pos + self.vel)[0] > self.SIZE): 49 self.vel[0] = -self.vel[0] 50 if (abs(self.pos + self.vel)[1] > self.SIZE): 51 self.vel[1] = -self.vel[1] 52 53 self.pos += self.vel#位置更新 54 self.vel_tmp = np.zeros(2)##進行速度ベクトル初期化 55 return True 56 57class AgentEdited(Agent): 58 def __init__(self, *args, **kwargs): 59 super(AgentEdited, self).__init__(*args, **kwargs) 60 #クラス(子クラス)で別のクラス(親クラス)を継承できます。継承することで、親クラスのメソッドを子クラスから呼び出せる 61 #super().親クラスのメソッド # python3系での標準の書き方 62 #super(親クラスのオブジェクト, self).親クラスのメソッド # python2系での書き方 63 #不特定多数の引数を受け取ることができる仕組みを作るのが「*args」「**kwargs」 64 self.color = kwargs.get('color', 'r') 65 66 def ruleSeparate(self, others, ratio = 1): 67 others = [other for other in others if self.distance(other) < self.RANGE_SEPARATE] 68 v = np.zeros(2) 69 if not others: 70 return 0 71 for other in others: 72 d = self.pos - other.pos 73 vel = self.vel - other.vel 74 TTNP = d / (vel + 1e-5) # 0除算防止のため微小値を挿入 75 DINP = self.distance(other) 76 v += 1/(1+np.exp(-(c1+d1*TTNP))) * 1/(1+np.exp(-(b1+a1*DINP))) 77 self.vel_tmp += v / len(others) * ratio 78 return v / len(others) * ratio 79 80 def calculate(self, others): 81 self.ruleSeparate(others) # only separate 82 83def calc_rad(pos2, pos1):#角計算 84 return np.arctan2(pos2[1] - pos1[1], pos2[0] - pos1[0]) 85 86#np.arctan(x)は引数が一つでarctan(x)をラジアンで返す。返り値は-pi / 2からpi / 2(-90度から90度)の間になる。 87#np.arctan2(y, x)は引数が二つで、arctan(y / x)をラジアンで返す。この角度は、極座標平面において原点から座標(x, y)へのベクトルがx軸の正の方向となす角度(偏角)であり、返り値は-piからpi(-180度から180度)の間になる 88#print(np.degrees(np.arctan2(-1, 1))) 89# -45.0 90#print(np.degrees(np.arctan2(1, -1))) 91# 135.0 92 93def rotate_vec(vec, rad):#ベクトル更新 94 return np.dot(vec, np.array([[np.cos(rad), -np.sin(rad)], [np.sin(rad), np.cos(rad)]]).T) 95 96class AgentGoForWall(AgentEdited): 97 def __init__(self, *args, **kwargs): 98 super(AgentGoForWall, self).__init__(*args, **kwargs) 99 self.color = kwargs.get('color', 'b') 100 max_distance = 0 101 self.goal = None # 角が一番遠い場所 102 for px in [-self.SIZE, self.SIZE]: 103 for py in [-self.SIZE, self.SIZE]: 104 dist = np.linalg.norm(self.pos - np.array([px, py])) 105 if max_distance < dist: 106 max_distance = dist#最大値の更新 107 self.goal = np.array([px, py]) 108 self.vel = rotate_vec(np.array([self.VEL, 0]), calc_rad(self.goal, self.pos)) 109 110 def update(self) -> bool: 111 self.vel += self.vel_tmp 112 self.vel += rotate_vec(np.array([self.VEL, 0]), calc_rad(self.goal, self.pos)) 113 114 v = np.linalg.norm(self.vel) 115 116 if abs(self.pos + self.vel)[0] > self.SIZE or abs(self.pos + self.vel)[1] > self.SIZE: 117 return False # deactivate this Agent 118 119 self.pos += self.vel 120 self.vel_tmp = np.zeros(2) 121 return True 122 123class Boids: 124 def __init__(self, AGENT = 20):#Agent数 125 self.agents = [Agent() for _ in range(AGENT)] 126 127 def calculate(self): 128 for agent in self.agents: 129 agent.calculate([other for other in self.agents if agent != other]) 130 131 def update(self): 132 self.agents = [agent for agent in self.agents if agent.update()] 133 134 def simulation(self): 135 self.calculate() 136 self.update() 137 138 def positions(self):#showimageはpos_arrayを渡してた 139 x, y, c = list(), list(), list() 140 for agent in self.agents: 141 x.append(agent.pos[0]) 142 y.append(agent.pos[1]) 143 c.append(agent.color) 144 return (np.array(x), np.array(y)), c 145 146np.random.seed( 0 ) 147B = Boids(AGENT = 2) 148B.agents.append(AgentEdited()) 149fig, ax = plt.subplots(figsize = (6, 6)) 150ax.set_xlim(-10, 10) 151ax.set_ylim(-10, 10) 152ax.grid(True) 153ims = [] 154for t in range(10): 155 B.simulation() 156 plot_data,plot_color = B.positions() 157 im=ax.scatter(*plot_data,"o",ms=5,c=plot_color) 158 ims.append(im) 159 #print(plot_data) 160 #print(plot_color) 161 162ani = animation.ArtistAnimation(fig, ims, interval=10, repeat=False) 163HTML(ani.to_jshtml())

試したこと

同様のエラー文に対する回答を探したが、解消には至らなかった。
https://stackoverflow.com/questions/35733223/matplotlib-scatter-plot-with-unknown-error

補足情報(FW/ツールのバージョンなど)

ここにより詳細な情報を記載してください。

気になる質問をクリップする

クリップした質問は、後からいつでもMYページで確認できます。

またクリップした質問に回答があった際、通知やメールを受け取ることができます。

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

guest

回答1

0

ベストアンサー

matplotlib.axes.Axes.scatterのドキュメントを見てみますと

Axes.scatter(x, y, s=None, c=None, marker=None, cmap=None, norm=None, vmin=None, vmax=None, alpha=None, linewidths=None, *, edgecolors=None, plotnonfinite=False, data=None, **kwargs)[source]

となっており、3番目の引数はsでマーカーのサイズになっております。また、質問のエラーとは関係ありませんが、Axes.scatterにおけるマーカーのサイズの指定を行うパラメータはmsではなく、sです。

Python

1im=ax.scatter(*plot_data,"o",ms=5,c=plot_color)

という書き方ですと、sに"o"が渡されてしまい、エラーが生じてしまいます。
順番通りに以下のように書くことでエラーは無くなると思います。

Python

1im=ax.scatter(*plot_data, 5, plot_color, 'o')

もしくは明示的に下記のように書くこともできます。

Python

1im=ax.scatter(*plot_data, marker="o", s=5, c=plot_color)

投稿2022/11/15 19:24

fixk

総合スコア70

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

IT_takumin

2022/11/16 13:22

ありがとうございました! 教えて頂いた通りにimを変更した上で ``` ims.append([im]) ``` とimsに追加する際にリスト化する事で解決できました。
guest

あなたの回答

tips

太字

斜体

打ち消し線

見出し

引用テキストの挿入

コードの挿入

リンクの挿入

リストの挿入

番号リストの挿入

表の挿入

水平線の挿入

プレビュー

15分調べてもわからないことは
teratailで質問しよう!

ただいまの回答率
85.48%

質問をまとめることで
思考を整理して素早く解決

テンプレート機能で
簡単に質問をまとめる

質問する

関連した質問