2016-06-20 50 views
1

我有在{test_size: (test_error, training_error)}這裏形式的字典,它是:Python3:使用matplotlib創造的人物,使用字典

{0.1: (0.94736842105263153, 0.90294117647058825), 0.2: (0.92105263157894735, 0.90397350993377479), 0.3: (0.82456140350877194, 0.9242424242424242), 0.6: (0.8722466960352423, 0.91390728476821192), 0.8: (0.76897689768976896, 0.98666666666666669), 0.5: (0.79894179894179895, 0.95767195767195767), 0.7: (0.8226415094339623, 0.99115044247787609), 0.9: (0.62463343108504399, 1.0), 0.4: (0.79605263157894735, 0.92920353982300885)} 

我想創建一個數字與matplotlib,看起來像這樣:

figure

我想獲得在x軸和y軸上的測試和訓練誤差詞典(中test_size)的關鍵。

如何解決這個問題?我應該使用DataFrame嗎?

df = pd.DataFrame(dictionary) 
plt.plot(df) 
??? 

我讀到的東西有關策劃字典只有使用Python 2 ..我使用Python 3有價值的,我真的失去了這個迄今爲止..希望有人能幫助!

回答

1

這個怎麼樣,

enter image description here


的源代碼,

import matplotlib.pyplot as plt 
import operator 

fig, ax = plt.subplots() 

d = {0.1: (0.94736842105263153, 0.90294117647058825), 0.2: (0.92105263157894735, 0.90397350993377479), 0.3: (0.82456140350877194, 0.9242424242424242), 0.6: (0.8722466960352423, 0.91390728476821192), 0.8: (0.76897689768976896, 0.98666666666666669), 0.5: (0.79894179894179895, 0.95767195767195767), 0.7: (0.8226415094339623, 0.99115044247787609), 0.9: (0.62463343108504399, 1.0), 0.4: (0.79605263157894735, 0.92920353982300885)} 
lists = sorted(d.items()) 

x = list(map(operator.itemgetter(0), lists)) 
y = list(map(operator.itemgetter(1), lists)) 

y1 = list(map(operator.itemgetter(0), y)) 
ax.plot(x, y1, label='Test error', color='b', linewidth=2) 

y2 = list(map(operator.itemgetter(1), y)) 
ax.plot(x, y2, label='Training error', color='r', linewidth=2) 

plt.legend(loc='best') 
plt.grid() 
plt.show() 
+0

感謝sparkandshine!不幸的是,你的代碼給了我這個錯誤:TypeError:float()參數必須是一個字符串或數字,而不是'map'。你知道如何解決這個問題嗎? – Papie

+0

我認爲地圖是在Python 2中使用的?你使用的是什麼版本的Python? – Papie

+0

@Papie,我使用Python2。對於Python3,嘗試用'list(y1)'替換'y1'。 – SparkAndShine