与 sns.barplot 一起绘制表格 [英] Plot table alongside sns.barplot

查看:77
本文介绍了与 sns.barplot 一起绘制表格的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

 #将数据读入数据框con = pd.read_csv('testOutput.csv')'''testOutput.csv 看起来像:样品数样本1,99.9样本2,96.6'''## 设置颜色随着值的增加而增加sns.set(style ="darkgrid")groupedvalues=con.groupby("Count").sum().reset_index()pal = sns.color_palette("Greens_d",len(groupedvalues))rank = groupedvalues ["Count"].argsort().argsort()#获取数据的汇总统计信息summary = pd.DataFrame(con ['Count'].describe())#设置限制maxLim = 100minLim=min(con['Count'])-0.1#barplot水平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))#移除标签g.set(yticks=[])g.set(xlabel='BLA BLA BLA', ylabel='样品')plt.table(cellText=summary.values,rowLabels = summary.index,colLabels = summary.columns,cellLoc = 'center', rowLoc = 'center',loc='右')#plt.show()plt.savefig('outTest.png',dpi = 150)

输出:图片右侧的这张桌子被剪掉了.我该如何解决这个问题,并且还要在标签上四舍五入到最接近的 0.1?

谢谢

解决方案

原则上,与

这还允许通过选择大于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)

使用专用子图

您可以使用专用的子图来放置表格.

 将matplotlib.pyplot导入为plt将numpy导入为np将熊猫作为pd导入df = pd.DataFrame({"count":np.sort(np.random.rand(100))* 100})摘要=pd.DataFrame(df['count'].describe())图,(ax,tabax)= plt.subplots(ncols = 2,gridspec_kw = dict(width_ratios = [2,1]))ax.barh(range(len(df)),df[count"])tabax.axis(关闭")tabax.table(cellText=summary.values,rowLabels=summary.index,colLabels=summary.columns,cellLoc ='right',rowLoc ='center',loc ='center')plt.savefig("out.png")plt.show()

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

This outputs : This table on the right of the image is cut off. How do I fix this and also just round down to nearest 0.1 on the labels please?

Thanks

解决方案

In principle, the same strategies than in this question's answer apply here.

Using bbox

You may freely position the table on your graph using the bbox argument, bbox = [left, bottom, width, height] where left, bottom, width, height are fractions of the axes.

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

This would also allow to put the table outside the axes by choosing the paramters larger than 1. In order to make space for the table, you can then shrink the subplots, 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)

Using dedicated subplot

You may use a dedicated subplot to put the table in.

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

这篇关于与 sns.barplot 一起绘制表格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆