并排绘制表sns.barp公司

2024-09-26 17:43:23 发布

您现在位置:Python中文网/ 问答频道 /正文

#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)

此输出:Test output 图像右侧的这张桌子被切断了。我该怎么解决这个问题呢?请把标签上的数字四舍五入到最接近的0.1?在

谢谢


Tags: csvsamplereaddatacountpltsummarycon
1条回答
网友
1楼 · 发布于 2024-09-26 17:43:23

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

使用bbox

您可以使用bbox参数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()

enter image description here

这也允许通过选择大于1的参数将工作台放在轴之外。为了给表腾出空间,然后可以收缩子批,plt.subplots_adjust(right=0.75)。在

^{pr2}$

enter image description here

使用专用子批次

您可以使用一个专用的子窗口来放置表。在

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()

enter image description here

相关问题 更多 >

    热门问题