如何在pandas数据框中按非字母顺序排序列,并合并matplotlib表格中的单元格?

2024-05-01 21:53:38 发布

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

我试图用python绘制一个表。我有它的工作方式…但是当我绘制我的表时,它并没有在我写表的末尾绘制通过/失败列。这些列似乎是按字母顺序显示的。在

  1. 如何禁用此功能。在
  2. 我想添加最后一列,但只作为一行。基本上是一个很大的复选框,但是当我这样做的时候,它会给我一个错误,即数组的长度必须相同,这是有意义的…但是我怎么能绕过这个问题,只拥有一个没有行的大列呢。。?在
import pandas as pd
import matplotlib.pyplot as plt

MinP_M=5
Min_M=6
Per_M=7
Per_G=8
Per2_M=9
PerFlat_M=10
MaxPL_M=11
Max_M=12
GF_M =13


fig1 = plt.figure()
fig1.set_size_inches(8.7,11.75,forward=True)
ax1=fig1.add_subplot(111)

ax1.axis('off')
ax1.axis('tight')

data2={'Min':['%s'%MinP_M,'%s'%Min_M,'',''],
       'Typ':['%s'%Per_M,'%s'%Per_G,'%s'%Per2_M,'+/- %s'%PerFlat_M],
       'Max':['%s'%MaxPL_M,'','%s'%Max_M,'+/- %s'%GF_M],
       'Pass/Fail':['','','','']
     }
df2 = pd.DataFrame(data2)

the_table2=ax1.table(cellText=df2.values,colWidths=[0.15]*5,rowLabels=['A','B','C', 'D'],colLabels=df2.columns,loc='center')

plt.show()

Tags: importas绘制pltminmaxpddf2
1条回答
网友
1楼 · 发布于 2024-05-01 21:53:38

第一部分比较容易解决。当您使用dict创建pandas数据帧时,关键字的顺序和列的顺序是不固定的。要获得正确的排序,请使用columns关键字。第二部分比较棘手。我找到的解决方案here是用第二个表覆盖原始表,然后在第二个表中添加另一个与原始表的四个单元格高度相同的单元格。为此,您必须首先从表实例中获取单元字典,并求出表行的高度。请参见以下代码:

import pandas as pd
import matplotlib.pyplot as plt

MinP_M=5
Min_M=6
Per_M=7
Per_G=8
Per2_M=9
PerFlat_M=10
MaxPL_M=11
Max_M=12
GF_M =13


fig1 = plt.figure()

##this line entirely messed up the plot for me (on Mac):
##fig1.set_size_inches(8.7,11.75,forward=True)

ax1=fig1.add_subplot(111)

ax1.axis('off')
ax1.axis('tight')

data2={'Min':['%s'%MinP_M,'%s'%Min_M,'',''],
       'Typ':['%s'%Per_M,'%s'%Per_G,'%s'%Per2_M,'+/- %s'%PerFlat_M],
       'Max':['%s'%MaxPL_M,'','%s'%Max_M,'+/- %s'%GF_M],
       'Pass/Fail':['','','','']
     }

##fix the column ordering with a list:
keys = ['Min', 'Typ', 'Max', 'Pass/Fail']
df2 = pd.DataFrame(data2, columns=keys)

##defining the size of the table cells
row_label_width = 0.05
col_width = 0.15
col_height = 0.05

the_table2=ax1.table(
    cellText=df2.values,
    colWidths=[col_width]*4,
    rowLabels=['A','B','C', 'D'],
    colLabels=df2.columns,
    ##loc='center', ##this has no effect if the bbox keyword is used
    bbox = [0,0,col_width*4,col_height*5],
)

celld = the_table2.get_celld()

##getting the heights of the header and the columns:
row_height_tot = 0
for (i,j),cell in celld.items():
    if j==3 and i>0:   #last column, but not the header
        row_height_tot += cell.get_height()    

the_table3=ax1.table(
    cellText=['0'], ##cannot be empty
    colLabels=df2.columns[-1:],
    colWidths=[col_width],
    bbox = [col_width*3,0,col_width,col_height*5],
)
the_table3.add_cell(1,0,col_width,row_height_tot)        

fig1.tight_layout()

plt.show()

我不得不关闭一些格式化选项,因为它们在我的电脑上给出了奇怪的结果。如果您想让表居中,请使用bbox命令中的bbox选项。最终结果如下: enter image description here

希望这有帮助。在

相关问题 更多 >