我在 csv 檔案中有非常簡單的資料集
condition,method,error
Normalized,LinfPGD,100
Integer,LinfPGD,100
Print Scan(U),LinfPGD,59
Print Scan(P),LinfPGD,9
Normalized,LinfBasicInteractive,100
Integer,LinfBasicInteractive,100
Print Scan(U),LinfBasicInteractive,69
Print Scan(P),LinfBasicInteractive,9
我想將它繪制在熊貓的條形圖中,但將“方法”列為主要結果,將“條件”列為子結果,將“錯誤”作為要繪制的值。
我從中得到的最接近的是使用交叉表
data=pd.read_csv('my_results.csv', sep=",")
pd.crosstab(data['method'], data['condition']).plot.bar(color=('DarkBlue', 'LightBlue', 'Teal'))
plt.tight_layout()
plt.show()
這回傳給我這個

這不是我想要的,因為交叉表會計算每個“條件”的數量,而我不希望這樣。我想要的只是考慮每個“方法”為每個“條件”繪制列“錯誤”。我還想將值放在每個條形圖的頂部。如何使用 Pandas/Matplotlib/Seaborn 做到這一點?
uj5u.com熱心網友回復:
您可以直接從原始資料框創建 seaborn barplot:
from matplotlib import pyplot as plt
import seaborn as sns
import pandas as pd
from io import StringIO
data_str = '''condition,method,error
Normalized,LinfPGD,100
Integer,LinfPGD,100
Print Scan(U),LinfPGD,59
Print Scan(P),LinfPGD,9
Normalized,LinfBasicInteractive,100
Integer,LinfBasicInteractive,100
Print Scan(U),LinfBasicInteractive,69
Print Scan(P),LinfBasicInteractive,9'''
data = pd.read_csv(StringIO(data_str), delimiter=',')
plt.figure(figsize=(12, 4))
sns.set_style('darkgrid')
ax = sns.barplot(data=data, x='method', y='error', hue='condition', palette=['darkblue', 'lightblue', 'teal'])
for bars in ax.containers:
ax.bar_label(bars)
ax.margins(y=0.1) # some extra space for the labels
plt.tight_layout()
plt.show()

uj5u.com熱心網友回復:
我認為我們可以使用 Pivot 來轉換資料框并創建圖表。
data = data.pivot(index='method', columns='condition', values='error')
data.plot.bar(color=('DarkBlue', 'LightBlue', 'Teal'))

轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/438517.html
標籤:Python 熊猫 matplotlib 海运
