【问题标题】:Kivy matplotlib -- How do I remove the extra white spaceKivy matplotlib -- 如何删除多余的空白
【发布时间】:2022-05-23 08:27:09
【问题描述】:

我在 Kivy 的 GUI 中有 matplotlib 我正在使用 FloatLayout 来放置我的小部件,但是当我在我的 GUI 中添加绘图时,它会在左侧添加一个额外的空白,所以我如何删除那个额外的空白,我尝试调整它的大小,但它不起作用,也没有响应我尝试进行的大小更改,任何帮助将不胜感激。

如果你没有kivy-garden

Start by installing kivy garden from here

然后你在 cmd 中运行这些命令

pip3 install matplotlib
garden install matplotlib

下面是我的代码:

from kivy.garden.matplotlib.backend_kivyagg import FigureCanvasKivyAgg
from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
import matplotlib.pyplot as plt
import numpy as np
from kivy.uix.floatlayout import FloatLayout


N = 5
menMeans = (20, 35, 30, 35, 27)
menStd = (2, 3, 4, 1, 2)

ind = np.arange(N)  # the x locations for the groups
width = 0.35       # the width of the bars

figure, ax = plt.subplots()
fig1 = plt.gcf()
rects1 = ax.bar(ind, menMeans, width, color='b', yerr=menStd)

womenMeans = (25, 32, 34, 20, 25)
womenStd = (3, 5, 2, 3, 3)
rects2 = ax.bar(ind + width, womenMeans, width, color='y', yerr=womenStd)

# add some text for labels, title and axes ticks
ax.set_ylabel('Scores')
ax.set_title('Scores by group and gender')
ax.set_xticks(ind + width)
ax.set_xticklabels(('G1', 'G2', 'G3', 'G4', 'G5'))
ax.legend((rects1[0], rects2[0]), ('Men', 'Women'))

def autolabel(rects):
# attach some text labels
    for rect in rects:
        height = rect.get_height()
        ax.text(rect.get_x() + rect.get_width() / 2., 1.05 * height, '%d' %
        int(height), ha='center', va='bottom')

autolabel(rects1)
autolabel(rects2)

plt.draw()


class MyApp(App):

    def build(self):
        box = FloatLayout()

        fig = FigureCanvasKivyAgg(plt.gcf())

        fig.size_hint_x = 0.5
        fig.size_hint_y =0.5
        fig.pos_hint={"x":0.32, "y": 0}
        box.add_widget(fig)
        return box

MyApp().run()

这是我要删除左侧多余空白的示例运行

【问题讨论】:

  • 这真的很奇怪,可能是 kivy garden 特有的东西。我可能会采取捷径并在顶部绘制一个黑色小部件,这不是一个很好的解决方案,但必须工作。
  • 我看到的是,当你增加它在 x 处的位置时,空白也会增加,但我尝试将它在 x 处的位置设置为零,这使得空白消失,这不是现在真的很好,它只允许你改变它在 y 处的位置。

标签: python matplotlib kivy python-3.7


【解决方案1】:

我不确定这一定是一个错误,但我至少可以看到空白的来源。在 FigureCanvasKivyAgg.draw() 方法中,它在绘制图形纹理贴图之前绘制了一个白色矩形:

201        with self.canvas:
202            Color(*color)
203            # Rectangle(pos=self.pos, size=(w, h))
204            Color(1.0, 1.0, 1.0, 1.0)
205            self.img_rect = Rectangle(texture=texture, pos=self.pos,

即使在更新画布时第一个 Rectangle 指令被清除,例如 on_size 事件,显然没有进一步的绘图指令与 on_size 或 python 模块中的其他回调相关联来填充画布的那部分用黑色或任何默认颜色。我注释掉了 Rectangle,并得到了正确的行为。由于我不知道 Rectangle 的真正原因,它可能会破坏其他东西。

【讨论】:

    猜你喜欢
    • 2018-06-02
    • 1970-01-01
    • 2022-01-19
    • 2013-05-14
    • 1970-01-01
    • 2021-10-16
    • 2013-05-19
    • 2021-10-07
    • 2016-12-28
    相关资源
    最近更新 更多