在 sns.barplot 旁边绘制 table

Plot table alongside sns.barplot

#read data into dataframe
con=pd.read_csv('testOutput.csv')

'''
testOutput.csv looks like :
Sample,Count
sample1,99.9
sample2, 96.6
'''


## set colours to increase with values
sns.set(style="darkgrid")
groupedvalues=con.groupby("Count").sum().reset_index()
pal = sns.color_palette("Greens_d", len(groupedvalues))
rank = groupedvalues["Count"].argsort().argsort()

#get summary stats of data
summary=pd.DataFrame(con['Count'].describe())
#set limits
maxLim=100
minLim=min(con['Count'])-0.1
#barplot horizontal
g=sns.barplot(x='Count', y ='Sample',data=groupedvalues,  palette=np.array(pal[::-1])[rank])
plt.xlim(minLim,maxLim)
plt.xticks(np.arange(minLim, 100, 0.1))
#remove labels
g.set(yticks=[])

g.set(xlabel='BLA BLA BLA', ylabel='Sample')
plt.table(cellText=summary.values,
          rowLabels=summary.index,
          colLabels=summary.columns,
          cellLoc = 'center', rowLoc = 'center',
          loc='right')
#plt.show()
plt.savefig('outTest.png', dpi=150)

这输出: 图片右边的这个table被截掉了。请问我该如何解决这个问题,并在标签上四舍五入到最接近的 0.1?

谢谢

原则上,与 this question 的答案相同的策略适用于此。

使用bbox

您可以使用 bbox 参数在图表上自由放置 table,bbox = [left, bottom, width, height] 其中 left, bottom, width, height 是轴的分数。

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

df = pd.DataFrame({"count" : np.sort(np.random.rand(100))*100})

summary=pd.DataFrame(df['count'].describe())

plt.barh(range(len(df)),df["count"])

plt.table(cellText=summary.values,
          rowLabels=summary.index,
          colLabels=summary.columns,
          cellLoc = 'right', rowLoc = 'center',
          loc='right', bbox=[.65,.05,.3,.5])

plt.savefig("out.png")
plt.show()

这也允许通过选择大于 1 的参数将 table 放在坐标轴之外。为了使 table 成为 space,您可以缩小子图,plt.subplots_adjust(right=0.75).

plt.table(cellText=summary.values,
          rowLabels=summary.index,
          colLabels=summary.columns,
          cellLoc = 'right', rowLoc = 'center',
          loc='right', bbox=[1,.3,.3,.5])

plt.subplots_adjust(right=0.75)

使用专用子图

您可以使用专用子图将 table 放入。

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

df = pd.DataFrame({"count" : np.sort(np.random.rand(100))*100})

summary=pd.DataFrame(df['count'].describe())

fig,(ax,tabax) = plt.subplots(ncols=2, gridspec_kw=dict(width_ratios=[2,1]))
ax.barh(range(len(df)),df["count"])

tabax.axis("off")
tabax.table(cellText=summary.values,
          rowLabels=summary.index,
          colLabels=summary.columns,
          cellLoc = 'right', rowLoc = 'center',
          loc='center')

plt.savefig("out.png")
plt.show()