格式化Matplotlib热图注释时出错

时间:2018-07-17 17:07:15

标签: python python-3.x matplotlib format heatmap

我正在尝试在matplotlib热图上设置注释的格式。这是我的代码。

x_axis_titles = ["Recession Probibility"]

spread = array([[3.0],
                [5.0],
                [10.0],
                [15.0],
                [20.0],
                [25.0],
                [30.0],
                [40.0],
                [50.0],
                [60.0],
                [70.0],
                [80.0],
                [90.0]])

spread_divisions = [1.35, 1.21, 0.76, 0.46, 0.22, 0.02, -0.17, -0.50, -0.82, -1.13, -1.46, -1.85, -2.40]
f = Figure(dpi=100)
ax = f.add_subplot(1,1,1)
ax.imshow(spread, cmap="bwr")

f.set_figwidth(3, forward=True)
f.set_figheight((root.winfo_height() / 100) - 4.0, forward=True)
ax.tick_params(axis='x', which='both', bottom=False, top=False, labelbottom=False)
ax.set_yticks(arange(len(spread_divisions)))
ax.set_yticklabels(spread_divisions)
for i in range(len(spread)):
    for j in range(len(x_axis_titles)):
        ax.text(j, i, '%.1f%' % spread[i, j], ha="center", va="center", color="w")

ax.set_title("Recession Probability\n\nCurrent Spread: " + str(round(dcf_data[9][-1] - (dcf_data[8][-1] * 100), 2)))

canvas = FigureCanvasTkAgg(f, master=dashboard_page)
canvas.show()
canvas.get_tk_widget().grid(row=1, column=0, columnspan=2, sticky=tkinter.W, padx=(10), pady=(5,5))

但是,我收到此错误:ValueError: incomplete format来自嵌套的for循环中的行ax.text(j, i, '%.1f%' % spread[i, j], ha="center", va="center", color="w")

我正尝试在下图所示的热图中向文本添加百分比符号。 Current Heatmap without "%"

感谢您的帮助!谢谢。

1 个答案:

答案 0 :(得分:0)

使用以下代码解决了此问题:

for i in range(len(spread)):
        for j in range(len(x_axis_titles)):
            ax.text(j, i, spread[i, j], ha="center", va="center", color="w")

for t in ax.texts: 
    t.set_text(t.get_text() + "%")