向Kivy MeshLinePlot添加多个图

时间:2019-01-08 22:20:45

标签: python kivy

我想在一个图形上添加多个图。以下示例仅添加在循环的最后一行中计算的数据。我如何实现我的目标?

注意:当使用不使用.kv文件的kivy示例并且在循环中运行多个'graph.add_plot'命令后添加了图形小部件时,我可以做到这一点。我还知道,使用.kv文件时,窗口小部件会自动更新,而从python代码运行时,它们不会自动更新。

from kivy.garden.graph import MeshLinePlot
from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
from kivy.lang import Builder
from math import sin

class RootWidget(BoxLayout):
    def __init__(self, **kwargs):
        super(RootWidget, self).__init__()
        self.plot = MeshLinePlot(color=[.5, .5, 1, 1])

    def start(self):
        #self.ids.graph.add_plot(self.plot) #same result if this line is added here
        for i in range(24):
            data_to_graph = [(x, sin(x)+ i) for x in range(0, 101)] #apply a DC offset to each trace to display multiple traces
            print(data_to_graph)
            self.plot.points =  data_to_graph
            self.ids.graph.add_plot(self.plot)

class GraphDemo(App):
    def build(self):
        return Builder.load_file("mainWindow_play.kv")

if __name__ == "__main__":
    GraphDemo().run()

mainWindow_play.kv

#:import MeshLinePlot kivy.garden.graph.MeshLinePlot
RootWidget:
    BoxLayout:
        orientation: "vertical"
        BoxLayout:
            size_hint: [1, .8]
            Graph:
                id: graph
                xlabel: "X"
                ylabel: "Y"
                y_ticks_major: 4
                x_ticks_major: 4
                y_grid_label: True
                x_grid_label: True
                padding: 5
                x_grid: True
                y_grid: True
                ymin: -1
                ymax: 25
                xmin: 0
                xmax: 25

        BoxLayout:
            size_hint: [1, .2]
            orientation: "horizontal"
            Button:
                text: "START"
                bold: True
                on_press: root.start()

1 个答案:

答案 0 :(得分:1)

您仅创建一个图,并且仅更改该图的图点。因此,最后的情节是最后一个情节。绘图只能添加到图形一次,因此,除第一个add_plot()外的所有内容都将被忽略。并且当更改绘图点时,将更新该绘图以显示最后的点。如果要查看所有图,则需要为每组数据点创建一个单独的图。也许像这样:

class RootWidget(BoxLayout):
    def __init__(self, **kwargs):
        super(RootWidget, self).__init__()

    def start(self):
        #self.ids.graph.add_plot(self.plot) #same result if this line is added here
        for i in range(24):
            data_to_graph = [(x, sin(x)+ i) for x in range(0, 101)] #apply a DC offset to each trace to display multiple traces
            print(data_to_graph)
            self.plot = MeshLinePlot(color=[.5, .5, 1, 1])
            self.plot.points =  data_to_graph
            self.ids.graph.add_plot(self.plot)

MeshLinePlot的创建移动到循环内部,以便您每次都创建一个新图并将其添加到图形中。