我正试图打印出一张seaborn
热图中单元格顶部的数字。例如,类似于:
ax = sns.heatmap(flights, annot=True, fmt=",")
(这是直接取自^{seaborn
,则可以开箱即用地运行相同的示例。)
这就产生了一个相当体面的人物,如下图所示:
但是,我希望看到数字四舍五入到最接近的百。换句话说,我希望看到像171这样的数字写成200,315写成300,等等
在引擎盖下,seaborn
实际上只是matplotlib
。我可以使用matplotlib
的^{
matplotlib
的文本依赖于python3的text formatting,它有方便的方法将舍入到小数点的右边,方法是做类似.2
四舍五入到第一百位***,但我找不到任何东西可以往另一个方向舍入。在
我可以简单地将数字四舍五入,然后再把它们推到绘图中,但这实际上会改变绘图数据本身,我宁愿避免这种情况。因此,我希望将传递给绘图的底层数字保持不变,同时仍然能够很好地打印内容。在
据我所知,要做到这一点,唯一的办法就是找到一种巧妙的方式来格式化事物。有办法吗?在
谢谢!在
我深入研究了^{
seaborn
代码中的相关行是:
但是,要使其工作,我需要能够修改我的pandas
dataframe列,这意味着我需要能够调整nd.array
元素的列。在
似乎有not yet any underlying ^{
所以,我暂时不想再讨论这个问题了,我希望一旦事情解决了,我将能够采用拉鲁伊的解决方案,事情应该“奏效”。在
一旦发生这种情况,解决办法是:
>>> class rndarray(np.ndarray):
... def __format__(self, spec):
... return np.ndarray.__format__(int(round(self, -2)), spec)
...
>>> df['<col_of_interest>'] = map(rndarray, df['<col_of_interest.'])
或者,如果不起作用,那么:
>>> df['<col_of_interest>'].values = map(rndarray, df['<col_of_interest.'].values)
您可以使用
int
的子类,并根据需要定义__format__
。在或者相当于浮点数
^{pr2}$编辑: 这个更老套的解决方案利用了
val = ("{:" + self.fmt + "}").format(val)
行。如果执行过程发生变化,可能会中断。在最好是能够传递一个
Formatter()
而不仅仅是一个fmt
字符串。在是的
为每一个细胞解决你的问题?在
相关问题 更多 >
编程相关推荐