在 Tkinter 中显示 Matplotlib spine

Display Matplotlib spines in Tkinter

我知道如何在 Matplotlib 中显示书脊。我也知道如何在 Tkinter 中显示 Matplotlib 子图。但我想知道如何将书脊放在 Tkinter 的这个子图中。

这是在 Tkinter 中显示子图的代码:

import matplotlib
matplotlib.use('TkAgg')

from numpy import arange, sin, pi
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg, NavigationToolbar2TkAgg
from matplotlib.figure import Figure

import sys
if sys.version_info[0] < 3:
    import Tkinter as Tk
else:
    import tkinter as Tk

def destroy(e): sys.exit()

root = Tk.Tk()
root.wm_title("Embedding in TK")

f = Figure(figsize=(5,4), dpi=100)
a = f.add_subplot(111)
t = arange(0.0,3.0,0.01)
s = sin(2*pi*t)

a.plot(t,s)
a.set_title('Tk embedding')
a.set_xlabel('X axis label')
a.set_ylabel('Y label')

# a tk.DrawingArea
canvas = FigureCanvasTkAgg(f, master=root)
canvas.show()
canvas.get_tk_widget().pack(side=Tk.TOP, fill=Tk.BOTH, expand=1)

#toolbar = NavigationToolbar2TkAgg( canvas, root )
#toolbar.update()
canvas._tkcanvas.pack(side=Tk.TOP, fill=Tk.BOTH, expand=1)

button = Tk.Button(master=root, text='Quit', command=sys.exit)
button.pack(side=Tk.BOTTOM)

Tk.mainloop()`

这是在 Matplotlib 中显示书脊的代码:

import numpy as np
import matplotlib.pyplot as plt


fig, ax = plt.subplots()

image = np.random.uniform(size=(10, 10))
ax.imshow(image, cmap=plt.cm.gray, interpolation='nearest')
ax.set_title('dropped spines')

# Move left and bottom spines outward by 10 points
ax.spines['left'].set_position(('outward', 10))
ax.spines['bottom'].set_position(('outward', 10))
# Hide the right and top spines
ax.spines['right'].set_visible(False)
ax.spines['top'].set_visible(False)
# Only show ticks on the left and bottom spines
ax.yaxis.set_ticks_position('left')
ax.xaxis.set_ticks_position('bottom')

plt.show()

在第二个代码块中使用 ax.set_title('...') 的地方,在第一个代码块中使用 a.set_title('...')。这几乎泄露了您可以在 ax 上调用的方法,您也可以在 a.

上调用

只需使用与第二个块中相同的代码,但将 ax 替换为 a,它应该可以正常工作。


根据文档,axa 不是完全相同的对象。 Figure.add_subplot() returns an Axes instance, and pyplot.subplots() returns an Axis 对象作为第二个输出参数。然而,由于

The Axes contains most of the figure elements: Axis...

您可以在两者中以相同的方式编辑书脊。