我想为以下代码生成的注释添加逗号分隔符,保留美元符号并使用set_text()
和get_text()
函数。我看到t返回一个“文本对象”,但我不知道如何修改对象以返回所需的结果。
如何在保持美元符号和使用for t in ax.texts
循环的同时添加逗号分隔符?
码:
import matplotlib.pyplot as plt
import pandas as pd
from random import randint
import seaborn as sns
#
datas = []
#
for item in list("ABC"):
for year in [2012, 2013, 2014, 2015, 2016, 2017]:
x = randint(1000, 2000)
datas.append([item, year, x])
df = pd.DataFrame(datas, columns = ["Item", "Year", "Value"])
df = df.pivot("Item", "Year", "Value")
ax = sns.heatmap(df, linewidths = 0.5, xticklabels = True, yticklabels = True, cmap = "OrRd", annot = True, fmt = "d")
for t in ax.texts:
t.set_text("$" + t.get_text())
plt.show()
Python字符串格式实际上有这个内置:
'${:,d}'.format(1000)
给'$1,000'
所以你可以试试
t.set_text('${:,d}'.format(int(t.get_text())))