[英]How to plot this kind of graph in Seaborn?
Department left
IT 0 0.777506
1 0.222494
RandD 0 0.846252
1 0.153748
accounting 0 0.734029
1 0.265971
hr 0 0.709066
1 0.290934
management 0 0.855556
1 0.144444
marketing 0 0.763403
1 0.236597
product_mng 0 0.780488
1 0.219512
sales 0 0.755072
1 0.244928
support 0 0.751009
1 0.248991
technical 0 0.743750
1 0.256250
這個使用pandas plot 1生成的圖: [https://i.stack.imgur.com/thBjs.png] 1當我們在pandas Hue中構建圖時,它是一個多索引數據框。 我需要與 seaborn 或 pyplot 中的完全相同。 提前感謝您的回復!!
首先,請注意 pandas plotting 和 seaborn 都只是 matplotlib 的一個接口。 matplotlib 和 seaborn 都可用於修飾和擴展熊貓圖。 例如,您可以將 seaborn 樣式應用於此類熊貓圖和plt.title('...')
以設置標題。
接下來,seaborn 更喜歡忽略索引並使用顯式列,而 Pandas 繪圖強烈依賴於索引。 您可以使用reset_index
將兩個索引都轉換為列。
下面是一個例子:
import matplotlib.pyplot as plt
import seaborn as sns
import pandas as pd
from io import StringIO
data_str = '''Department left value
IT 0 0.777506
IT 1 0.222494
RandD 0 0.846252
RandD 1 0.153748
accounting 0 0.734029
accounting 1 0.265971
hr 0 0.709066
hr 1 0.290934
management 0 0.855556
management 1 0.144444
marketing 0 0.763403
marketing 1 0.236597
product_mng 0 0.780488
product_mng 1 0.219512
sales 0 0.755072
sales 1 0.244928
support 0 0.751009
support 1 0.248991
technical 0 0.743750
technical 1 0.256250'''
# create a dataframe similar to the given one
df = pd.read_csv(StringIO(data_str), delim_whitespace=True)
df = df.set_index(['Department', 'left'])
sns.set_style('darkgrid') # this also works with pandas
fig, ax = plt.subplots(figsize=(14, 3))
# use reset_index so seaborn can work with them as columns
sns.barplot(data=df.reset_index(), x='Department', y='value', hue='left', ax=ax)
plt.tight_layout()
plt.show()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.