首页 > 解决方案 > 在 seaborn 图下方添加一个表格

问题描述

我已经看到了很多关于这个的东西,但我似乎无法让它发挥作用,所以我想我会问。

我想生成这样的图,图下方的表格显示每个类别的计数。谁能帮我吗?

import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
import numpy as np

data = {'Category': ['a', 'a', 'a', 'a', 'a', 'b', 'b', 'b', 'c', 'c'],
        'var1': [1, 2, 2, 4, 5, 3, 4, 5, 4, 7],
        'var2': [2, 4, 8, 9, 4, 2, 3, 8, 3, 7]}

df = pd.DataFrame(data)

print(df.head(15))

sns.jointplot(data=df, x='var1', y='var2', hue='Category')

plt.suptitle('Example Data')

plt.show()

在此处输入图像描述

理想情况下,我希望它看起来像这样:

           Plot Stuff
     _______________________
    | Category | a | b | c |
    ------------------------
    |   Count  | 5 | 3 | 2 | 
    ------------------------   

编辑:

我已经更新了脚本,如下所示。我不能让表格居中,我只能让它出现在情节的右侧,我需要它在情节下方,但上面也可以。

import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
import numpy as np

data = {'Category': ['a', 'a', 'a', 'a', 'a', 'b', 'b', 'b', 'c', 'c'],
        'var1': [1, 2, 2, 4, 5, 3, 4, 5, 4, 7],
        'var2': [2, 4, 8, 9, 4, 2, 3, 8, 3, 7]}

df = pd.DataFrame(data)

print(df.head(15))

sns.jointplot(data=df, x='var1', y='var2', hue='Category')

plt.suptitle('Example Data')

plt.table(cellText=df.values,
          rowLabels=df.index,
          colLabels=df.columns,
          cellLoc = 'center', rowLoc = 'center',
          loc='bottom')

plt.subplots_adjust(left=0.2, bottom=0.2)

plt.show()

在此处输入图像描述

标签: pythonmatplotlibseaborn

解决方案


您可以使用bbox手动将表格居中,这是您的代码bbox并调整了字体大小:

import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
import numpy as np

data = {'Category': ['a', 'a', 'a', 'a', 'a', 'b', 'b', 'b', 'c', 'c'],
        'var1': [1, 2, 2, 4, 5, 3, 4, 5, 4, 7],
        'var2': [2, 4, 8, 9, 4, 2, 3, 8, 3, 7]}

df = pd.DataFrame(data)

print(df.head(15))

sns.jointplot(data=df, x='var1', y='var2', hue='Category')

plt.suptitle('Example Data')

table = plt.table(cellText=df.values,
          rowLabels=df.index,
          colLabels=df.columns,
          bbox=(-6, -0.65, 6, 0.5))
table.auto_set_font_size(False)
table.set_fontsize(12)

plt.show()

结果图片


推荐阅读