[英]How can I plot a simple plot with seaborn from a python dictionary?
[英]How can I plot a heatmap from my python dictionary?
我有一個 python 字典,其鍵是棋盤位置(64 個位置),其值是在棋盤 position 上發生的捕獲次數。
OrderedDict([('a1', 552),
('a2', 1128),
('a3', 1464),
('a4', 2328),
('a5', 2304),
('a6', 2088),
('a7', 1344),
('a8', 768),
('b1', 504),
('b2', 2544),
('b3', 3480),
('b4', 5016),
...
('h5', 2136),
('h6', 1968),
('h7', 816),
('h8', 336)])
為了找到棋盤上最“危險”的位置,我希望使用 seaborn 將 plot 這些值放到熱圖中。 為此,應將數據轉換為 pandas dataframe 或 numpy 數組,其中行范圍從1到8 ,列范圍從a到h (參見。 我需要一個與所示棋盤布局完全相同的數據框。
如何將此“線性”數據轉換為二維布局?
你可以試試:
# this would make `a`-`h` as rows
# transpose the data if you like
data = np.array(list(your_dict.values()) ).reshape(8,8)
plt.imshow(data, cmap='hot')
Seaborn 熱量 map 非常簡單。 已生成完整的OrderedDict
來演示。
from collections import OrderedDict
import random
import numpy as np;
import seaborn as sns
cb = OrderedDict([(f"{c}{r}",random.randint(300,5000)) for c in "abcdefgh" for r in range(8,0,-1)])
ax = sns.heatmap(np.array([bpv for bp, bpv in cb.items()]).reshape(8,8))
ylabel = ax.set_yticklabels(np.array([bp[-1] for bp, bpv in cb.items()]).reshape(8,8)[0])
xlabel = ax.set_xticklabels(np.array([bp[0] for bp, bpv in cb.items()]).reshape(8,8)[:,0])
我在@Quang Hoang 的幫助下找到了解決方案:
data = np.array(list(dic.values()) ).reshape(8,8) # transform to 2D
data = data.transpose() # transpose (swap rows with columns)
data = np.flipud(data) # flip vertically to match chessboard layout
data
它返回:
array([[ 768, 600, 1896, 2592, 1440, 1008, 144, 336],
[ 1344, 2304, 1512, 3192, 3096, 2712, 2280, 816],
[ 2088, 2664, 5952, 5472, 4536, 7152, 3192, 1968],
[ 2304, 4872, 7608, 16656, 11544, 6408, 4464, 2136],
[ 2328, 5016, 7464, 15168, 9912, 5544, 3720, 2040],
[ 1464, 3480, 6048, 4128, 4008, 5304, 3264, 1488],
[ 1128, 2544, 1920, 2568, 2784, 1968, 2232, 720],
[ 552, 504, 1776, 1968, 1464, 1248, 288, 456]])
這與原始帖子中引用的棋盤布局完全匹配。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.