2016-05-09 10 views
1

私は散布図を辞書の辞書に散布する必要があります。辞書の散布図辞書

私のデータは次のようになります。外側のキーはx軸のラベルと内側の鍵である

{'+C': {1: 191, 2: 557}, '+B': None, '-B': None, '+D': None, '+N': {1: 1, 3: 1}, '+L': {1: 2819, 2: 1506}, '>L': None, '<C': {0: 2125}, '<B': None, '<L': {0: 2949, 1: 2062}} 

をy軸です。内部キーの値は、x、yの注釈です。私はデータをプロットしようとしましたが、私が探していたグラフが得られませんでした。

私は以下を試しましたが、私のx軸に繰り返しがありました。

for action, value in action_sequence.items(): 
     if value: 
      for seq,count in value.items(): 
       data["x"].append(action) 
       data["y"].append(seq) 
       data["label"].append(count) 
     else: 
      data["x"].append(action) 
      data["y"].append(-1) 
      data["label"].append(0) 

print(data) 

plt.figure(figsize=(10,8)) 
plt.title('Scatter Plot', fontsize=20) 
plt.xlabel('x', fontsize=15) 
plt.ylabel('y', fontsize=15) 
plt.xticks(range(len(data["x"])), data["x"]) 
plt.scatter(range(len(data["x"])), data["y"], marker = 'o') 

答えて

0

xの整数カテゴリを設定して、x軸にラベルを割り当てる必要があります。以下のコードはあなたのdictのアクションコードを使用しています。 Pythonの辞書は順序がないので、キーをソートする必要があることに注意してください。代わりに、順序付けされたdictを使用し、dict.keys()を直接使用することもできます。

各点の注釈は、プロット上にテキスト注釈を付けて一度に1つずつ配置される文字列です。 plt.axis()を使ってプロットのx軸、y軸の範囲を明示的に設定する必要があります。これは、範囲を自動的に計算するときに注釈が含まれないためです。

Matplotlib: How to put individual tags for a scatter plot

import matplotlib.pyplot as plt 

action_sequence = { 
    '+C': {1: 191, 2: 557}, '+B': None, '-B': None, '+D': None, 
    '+N': {1: 1, 3: 1}, '+L': {1: 2819, 2: 1506}, 
    '>L': None, '<C': {0: 2125}, '<B': None, '<L': {0: 2949, 1: 2062} 
} 

# x data are categorical; define a lookup table mapping category string to int 
x_labels = list(sorted(action_sequence.keys())) 
x_values = list(range(len(x_labels))) 
lookup_table = dict((v,k) for k,v in enumerate(x_labels)) 

# Build a list of points (x, y, annotation) defining the scatter plot. 
points = [(lookup_table[action], key, anno) 
     for action, values in action_sequence.items() 
     for key, anno in (values if values else {}).items()] 
x, y, anno = zip(*points) 

# y is also categorical, with integer labels for the categories 
y_values = list(range(min(y), max(y)+1)) 
y_labels = [str(v) for v in y_values] 

plt.figure(figsize=(10,8)) 
plt.title('Scatter Plot', fontsize=20) 
plt.xlabel('x', fontsize=15) 
plt.ylabel('y', fontsize=15) 
plt.xticks(x_values, x_labels) 
plt.yticks(y_values, y_labels) 
plt.axis([min(x_values)-0.5, max(x_values)+0.5, 
      min(y_values)-0.5, max(y_values)+0.5]) 
#plt.scatter(x, y, marker = 'o') 
for x_k, y_k, anno_k in points: 
    plt.text(x_k, y_k, str(anno_k)) 

plt.show() 

は、散布図を標識するさまざまな方法については、次の質問を参照してください。