窗口外的Matplotlib图形注释

时间:2018-07-07 01:22:59

标签: python-3.x matplotlib tkinter

我正在制作一个在tkinter窗口中实现matplotlib饼图/甜甜圈图的程序,以说明一些数据,但是,我从饼图的每个楔形中添加了“注释”或标签。因此,执行代码时打开的窗口适合图表本身,但是标签在窗口的边缘被切除。具体来说,看起来像这样... enter image description here

请注意,顶部两个箭头实际上没有在相应标签上附加文本,因此情况实际上比我的屏幕快照更糟。

即使我摆脱了与生成tkinter GUI相关的代码,也只是尝试执行代码以生成常规图形窗口,标签最初还是被切除了。但是,如果我使用内置的缩小功能,则可以缩小标签的大小。

我试图在这里调整无花果的大小...

fig, ax = plt.subplots(figsize=(6, 4), subplot_kw=dict(aspect="equal"))

但是没有什么区别。希望有解决方案,谢谢...

这是我的完整代码,如果有人需要...

import numpy as np
import matplotlib.pyplot as plt

player1_cards = {'Mustard', 'Plum', 'Revolver', 'Rope', 'Ballroom', 'Library'}
player2_cards = {'Scarlet', 'White', 'Candlestick'}
player3_cards = {'Green', 'Library', 'Kitchen', 'Conservatory'}
middle_cards = {'Peacock'}
unknown_cards = {'Lead Pipe', 'Wrench', 'Knife', 'Hall', 'Lounge', 'Dining Room', 'Study'}

player1_string = ', '.join(player1_cards)
player1_string = player1_string.replace(', ', '\n')

player2_string = ', '.join(player2_cards)
player2_string = player2_string.replace(', ', '\n')

player3_string = ', '.join(player3_cards)
player3_string = player3_string.replace(', ', '\n')

fig, ax = plt.subplots(figsize=(6, 4), subplot_kw=dict(aspect="equal"))

recipe = [player1_string, player2_string, player3_string, '', '']
data = [len(player1_cards), len(player2_cards), len(player3_cards), 1, 7]
cols = ['#339E5A', '#26823E', '#0C5D2E', '#98D6AE', '#5EC488']

wedges, texts = ax.pie(data, wedgeprops=dict(width=0.5), startangle=90, colors = cols)

for w in wedges:
    w.set_linewidth(4)
    w.set_edgecolor('white')

bbox_props = dict(boxstyle="square,pad=0.3", fc="w", ec="white", lw=0.72)
kw = dict(xycoords='data', textcoords='data',  arrowprops=dict(arrowstyle="-"), bbox=bbox_props, zorder=0, va="center")

for i, p in enumerate(wedges):
    ang = (p.theta2 - p.theta1)/2. + p.theta1
    y = np.sin(np.deg2rad(ang))
    x = np.cos(np.deg2rad(ang))
    horizontalalignment = {-1: "right", 1: "left"}[int(np.sign(x))]
    connectionstyle = "angle,angleA=0,angleB={}".format(ang)
    kw["arrowprops"].update({"connectionstyle": connectionstyle})
    ax.annotate(recipe[i], xy=(x, y), xytext=(x + np.sign(x)*.5, y*1.5),
             horizontalalignment=horizontalalignment, **kw, family = "Quicksand")

ax.set_title("Matplotlib bakery: A donut")

plt.show()

1 个答案:

答案 0 :(得分:2)

您可能需要使用subplot参数来为轴外的文本留出空间。

fig.subplots_adjust(bottom=..., top=..., left=..., right=...)

例如在这种情况下

fig.subplots_adjust(bottom=0.2, top=0.9)

似乎可以很好地表达出来

enter image description here