【问题标题】:How to plot this kind of graph in Seaborn?如何在 Seaborn 中绘制这种图表?
【发布时间】:2021-12-19 07:29:19
【问题描述】:
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

This graph generated using pandas plot 1: [https://i.stack.imgur.com/thBjs.png]1 当我们在 pandas hue 中构建图形时,它是一个多索引数据框。我需要与 seaborn 或 pyplot 中的完全相同。提前感谢您的回复!

【问题讨论】:

标签: python pandas dataframe matplotlib seaborn


【解决方案1】:

首先,请注意,pandas 绘图和 seaborn 都只是 matplotlib 的一个接口。 matplotlib 和 seaborn 都可以用来修饰和扩展熊猫图。例如。您可以将 seaborn 样式应用到这样的 pandas 情节和 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()

【讨论】:

  • 如果这回答了您的问题,您可能会将marking 的答案视为已接受。
猜你喜欢
  • 2019-01-16
  • 1970-01-01
  • 2021-01-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-05-04
相关资源
最近更新 更多