繁体   English   中英

与sns.barplot一起的绘图表

[英]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)

输出: 测试输出 图像右侧的该表被切除。 我该如何解决这个问题,并且还要将标签上的数值四舍五入到最接近的0.1?

谢谢

原则上,此处采用与该问题的答案相同的策略。

使用bbox

您可以使用bbox参数bbox = [left, bottom, width, height]在其中自由放置表格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的参数将表格放置在轴外。为了为表格腾出空间,您可以缩小子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()

在此处输入图片说明

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM