原则上,与中的策略相同这个问题 https://stackoverflow.com/questions/44401394/how-to-adjust-table-for-a-plot-more-space-for-table-and-graph-matplotlib-python的答案适用于此。
Using bbox
您可以使用以下命令在图表上自由定位表格bbox
争论,bbox = [left, bottom, width, height]
where 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 的参数将表格放在轴之外。为了为表格腾出空间,您可以缩小子图,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)
使用专用子图
您可以使用专用的子图来放置表格。
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()