【问题标题】:Matplotlib figure annotations outside of window窗口外的 Matplotlib 图形注释
【发布时间】:2018-07-07 01:22:58
【问题描述】:

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

请注意,顶部的两个箭头实际上并没有将文本附加到相应的标签上,因此情况实际上比我的屏幕截图所描述的要糟糕。

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

我已经尝试在这里调整 figsize...

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()

【问题讨论】:

  • 有什么原因,为什么你在wedges上循环两次?

标签: python-3.x matplotlib tkinter


【解决方案1】:

您可能希望使用 subplot 参数来为轴外的文本腾出空间。

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

例如在这种情况下

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

似乎给出了一个很好的表示

【讨论】:

  • 嗨。您的屏幕截图准确地描述了我正在寻找的内容。但是,我有点困惑在我的程序中在哪里实现这行代码。我对 matplotlib 真的很陌生。非常感谢您帮助我解决了我的问题。
  • 您可以将其放置在定义图形的点和 show 它的点之间的任何位置。
猜你喜欢
  • 2015-01-14
  • 1970-01-01
  • 2016-10-13
  • 2018-08-02
  • 1970-01-01
  • 2017-10-18
  • 1970-01-01
  • 2017-10-17
  • 1970-01-01
相关资源
最近更新 更多