Matplotlib heatmap in a kivy window











up vote
0
down vote

favorite












I want to put a Matplotlib heatmap inside a kivy screen and also be able to move back and forth between the heatmap screen and the main screen.
Now the main problem is that i have to make that heatmap change dynamically, to show realtime changes.



i'm pasting my code here:



    import matplotlib
matplotlib.use('module://kivy.garden.matplotlib.backend_kivy')
from matplotlib.figure import Figure
from numpy import arange, sin, pi
from kivy.app import App

import numpy as np
from kivy.garden.matplotlib.backend_kivyagg import
FigureCanvasKivyAgg,FigureCanvas,NavigationToolbar2Kivy
from kivy.uix.floatlayout import FloatLayout
from kivy.uix.boxlayout import BoxLayout
from matplotlib.transforms import Bbox
from kivy.uix.button import Button
from kivy.graphics import Color, Line, Rectangle

import matplotlib.pyplot as plt

import random




def heatmap(fig, row_labels="", col_labels="", ax=None,
cbar_kw={}, cbarlabel="",*largs, **kwargs):
print("refresh")

count=random.randint(0,3)
if count==0:
data=np.loadtxt('datafile.txt')
elif count==1:
data=np.loadtxt('datafile1.txt')
elif count==2:
data=np.loadtxt('datafile2.txt')
elif count==3:
data=np.loadtxt('datafile3.txt')


if not ax:
ax = plt.gca()

# Plot the heatmap
obj=ax.imshow(data,aspect='auto', **kwargs)

#this is to block some cells for a particular purpose
n=""
for i in range(12):
for j in range(27):
if data[i,j]==-1:
n="b"
else : n=" "
text = ax.text(j, i, n,ha="center", va="baseline", color="b")

# Create colorbar
cbar = ax.figure.colorbar(obj, ax=ax, **cbar_kw)
cbar.ax.set_ylabel(cbarlabel, rotation=-90, va="bottom")
ax.set_title("title")
#fig.tight_layout()
#fig.savefig("sample_plot.png",bbox_inches='tight',transparent=True)
im=fig.canvas
return im






"""
def callback(instance):
#heatmap(fig,ax,cmap="inferno_r", cbarlabel="density")
#canvas = fig.canvas
fig, ax = plt.subplots()
heatmap(fig,ax,cmap="inferno_r", cbarlabel="density")
self.im=FigureCanvasKivyAgg(plt.gcf())
"""



class MatplotlibTest(App):
title = 'Matplotlib Test'
def refresh(self,instance):
fig, ax = plt.subplots()
heatmap(fig,ax,cmap="inferno_r", cbarlabel="density")
plt.close('all')
self.im=FigureCanvasKivyAgg(plt.gcf())

def build(self):
fig, ax = plt.subplots()
heatmap(fig,ax,cmap="inferno_r", cbarlabel="density")
self.im=FigureCanvasKivyAgg(plt.gcf())
fl = BoxLayout(orientation="vertical")
a = Button(text="refresh", height=40, size_hint_y=None)
a.bind(on_release=self.refresh)

fl.add_widget(self.im)

fl.add_widget(a)
return fl

if __name__ == '__main__':
MatplotlibTest().run()


I'm trying to get this code to refresh and plot new data in the heatmap on realeasing the refresh button. But that's not happening. I'm unable to clear the plt.gcf() reference and load and plot a new one.



I've tried all the plt.gcf().clear() , plt.close(), plt.Close('all'), plt.close('fig'), cleared axses and everything. Nothing works



There is no .KV file for this one, its going to run as it is, but not going to be dynamically changing (which is the primary requirement).



Also it would be extremely helpful if you could show me how to confine the plotting to one screen so i can move around multiple screens using kivy.uix.screenmanager.



PS: I know there are many stupid mistakes here, and that is exactly why I'm here asking for help.



All help is appreciated. :)










share|improve this question




























    up vote
    0
    down vote

    favorite












    I want to put a Matplotlib heatmap inside a kivy screen and also be able to move back and forth between the heatmap screen and the main screen.
    Now the main problem is that i have to make that heatmap change dynamically, to show realtime changes.



    i'm pasting my code here:



        import matplotlib
    matplotlib.use('module://kivy.garden.matplotlib.backend_kivy')
    from matplotlib.figure import Figure
    from numpy import arange, sin, pi
    from kivy.app import App

    import numpy as np
    from kivy.garden.matplotlib.backend_kivyagg import
    FigureCanvasKivyAgg,FigureCanvas,NavigationToolbar2Kivy
    from kivy.uix.floatlayout import FloatLayout
    from kivy.uix.boxlayout import BoxLayout
    from matplotlib.transforms import Bbox
    from kivy.uix.button import Button
    from kivy.graphics import Color, Line, Rectangle

    import matplotlib.pyplot as plt

    import random




    def heatmap(fig, row_labels="", col_labels="", ax=None,
    cbar_kw={}, cbarlabel="",*largs, **kwargs):
    print("refresh")

    count=random.randint(0,3)
    if count==0:
    data=np.loadtxt('datafile.txt')
    elif count==1:
    data=np.loadtxt('datafile1.txt')
    elif count==2:
    data=np.loadtxt('datafile2.txt')
    elif count==3:
    data=np.loadtxt('datafile3.txt')


    if not ax:
    ax = plt.gca()

    # Plot the heatmap
    obj=ax.imshow(data,aspect='auto', **kwargs)

    #this is to block some cells for a particular purpose
    n=""
    for i in range(12):
    for j in range(27):
    if data[i,j]==-1:
    n="b"
    else : n=" "
    text = ax.text(j, i, n,ha="center", va="baseline", color="b")

    # Create colorbar
    cbar = ax.figure.colorbar(obj, ax=ax, **cbar_kw)
    cbar.ax.set_ylabel(cbarlabel, rotation=-90, va="bottom")
    ax.set_title("title")
    #fig.tight_layout()
    #fig.savefig("sample_plot.png",bbox_inches='tight',transparent=True)
    im=fig.canvas
    return im






    """
    def callback(instance):
    #heatmap(fig,ax,cmap="inferno_r", cbarlabel="density")
    #canvas = fig.canvas
    fig, ax = plt.subplots()
    heatmap(fig,ax,cmap="inferno_r", cbarlabel="density")
    self.im=FigureCanvasKivyAgg(plt.gcf())
    """



    class MatplotlibTest(App):
    title = 'Matplotlib Test'
    def refresh(self,instance):
    fig, ax = plt.subplots()
    heatmap(fig,ax,cmap="inferno_r", cbarlabel="density")
    plt.close('all')
    self.im=FigureCanvasKivyAgg(plt.gcf())

    def build(self):
    fig, ax = plt.subplots()
    heatmap(fig,ax,cmap="inferno_r", cbarlabel="density")
    self.im=FigureCanvasKivyAgg(plt.gcf())
    fl = BoxLayout(orientation="vertical")
    a = Button(text="refresh", height=40, size_hint_y=None)
    a.bind(on_release=self.refresh)

    fl.add_widget(self.im)

    fl.add_widget(a)
    return fl

    if __name__ == '__main__':
    MatplotlibTest().run()


    I'm trying to get this code to refresh and plot new data in the heatmap on realeasing the refresh button. But that's not happening. I'm unable to clear the plt.gcf() reference and load and plot a new one.



    I've tried all the plt.gcf().clear() , plt.close(), plt.Close('all'), plt.close('fig'), cleared axses and everything. Nothing works



    There is no .KV file for this one, its going to run as it is, but not going to be dynamically changing (which is the primary requirement).



    Also it would be extremely helpful if you could show me how to confine the plotting to one screen so i can move around multiple screens using kivy.uix.screenmanager.



    PS: I know there are many stupid mistakes here, and that is exactly why I'm here asking for help.



    All help is appreciated. :)










    share|improve this question


























      up vote
      0
      down vote

      favorite









      up vote
      0
      down vote

      favorite











      I want to put a Matplotlib heatmap inside a kivy screen and also be able to move back and forth between the heatmap screen and the main screen.
      Now the main problem is that i have to make that heatmap change dynamically, to show realtime changes.



      i'm pasting my code here:



          import matplotlib
      matplotlib.use('module://kivy.garden.matplotlib.backend_kivy')
      from matplotlib.figure import Figure
      from numpy import arange, sin, pi
      from kivy.app import App

      import numpy as np
      from kivy.garden.matplotlib.backend_kivyagg import
      FigureCanvasKivyAgg,FigureCanvas,NavigationToolbar2Kivy
      from kivy.uix.floatlayout import FloatLayout
      from kivy.uix.boxlayout import BoxLayout
      from matplotlib.transforms import Bbox
      from kivy.uix.button import Button
      from kivy.graphics import Color, Line, Rectangle

      import matplotlib.pyplot as plt

      import random




      def heatmap(fig, row_labels="", col_labels="", ax=None,
      cbar_kw={}, cbarlabel="",*largs, **kwargs):
      print("refresh")

      count=random.randint(0,3)
      if count==0:
      data=np.loadtxt('datafile.txt')
      elif count==1:
      data=np.loadtxt('datafile1.txt')
      elif count==2:
      data=np.loadtxt('datafile2.txt')
      elif count==3:
      data=np.loadtxt('datafile3.txt')


      if not ax:
      ax = plt.gca()

      # Plot the heatmap
      obj=ax.imshow(data,aspect='auto', **kwargs)

      #this is to block some cells for a particular purpose
      n=""
      for i in range(12):
      for j in range(27):
      if data[i,j]==-1:
      n="b"
      else : n=" "
      text = ax.text(j, i, n,ha="center", va="baseline", color="b")

      # Create colorbar
      cbar = ax.figure.colorbar(obj, ax=ax, **cbar_kw)
      cbar.ax.set_ylabel(cbarlabel, rotation=-90, va="bottom")
      ax.set_title("title")
      #fig.tight_layout()
      #fig.savefig("sample_plot.png",bbox_inches='tight',transparent=True)
      im=fig.canvas
      return im






      """
      def callback(instance):
      #heatmap(fig,ax,cmap="inferno_r", cbarlabel="density")
      #canvas = fig.canvas
      fig, ax = plt.subplots()
      heatmap(fig,ax,cmap="inferno_r", cbarlabel="density")
      self.im=FigureCanvasKivyAgg(plt.gcf())
      """



      class MatplotlibTest(App):
      title = 'Matplotlib Test'
      def refresh(self,instance):
      fig, ax = plt.subplots()
      heatmap(fig,ax,cmap="inferno_r", cbarlabel="density")
      plt.close('all')
      self.im=FigureCanvasKivyAgg(plt.gcf())

      def build(self):
      fig, ax = plt.subplots()
      heatmap(fig,ax,cmap="inferno_r", cbarlabel="density")
      self.im=FigureCanvasKivyAgg(plt.gcf())
      fl = BoxLayout(orientation="vertical")
      a = Button(text="refresh", height=40, size_hint_y=None)
      a.bind(on_release=self.refresh)

      fl.add_widget(self.im)

      fl.add_widget(a)
      return fl

      if __name__ == '__main__':
      MatplotlibTest().run()


      I'm trying to get this code to refresh and plot new data in the heatmap on realeasing the refresh button. But that's not happening. I'm unable to clear the plt.gcf() reference and load and plot a new one.



      I've tried all the plt.gcf().clear() , plt.close(), plt.Close('all'), plt.close('fig'), cleared axses and everything. Nothing works



      There is no .KV file for this one, its going to run as it is, but not going to be dynamically changing (which is the primary requirement).



      Also it would be extremely helpful if you could show me how to confine the plotting to one screen so i can move around multiple screens using kivy.uix.screenmanager.



      PS: I know there are many stupid mistakes here, and that is exactly why I'm here asking for help.



      All help is appreciated. :)










      share|improve this question















      I want to put a Matplotlib heatmap inside a kivy screen and also be able to move back and forth between the heatmap screen and the main screen.
      Now the main problem is that i have to make that heatmap change dynamically, to show realtime changes.



      i'm pasting my code here:



          import matplotlib
      matplotlib.use('module://kivy.garden.matplotlib.backend_kivy')
      from matplotlib.figure import Figure
      from numpy import arange, sin, pi
      from kivy.app import App

      import numpy as np
      from kivy.garden.matplotlib.backend_kivyagg import
      FigureCanvasKivyAgg,FigureCanvas,NavigationToolbar2Kivy
      from kivy.uix.floatlayout import FloatLayout
      from kivy.uix.boxlayout import BoxLayout
      from matplotlib.transforms import Bbox
      from kivy.uix.button import Button
      from kivy.graphics import Color, Line, Rectangle

      import matplotlib.pyplot as plt

      import random




      def heatmap(fig, row_labels="", col_labels="", ax=None,
      cbar_kw={}, cbarlabel="",*largs, **kwargs):
      print("refresh")

      count=random.randint(0,3)
      if count==0:
      data=np.loadtxt('datafile.txt')
      elif count==1:
      data=np.loadtxt('datafile1.txt')
      elif count==2:
      data=np.loadtxt('datafile2.txt')
      elif count==3:
      data=np.loadtxt('datafile3.txt')


      if not ax:
      ax = plt.gca()

      # Plot the heatmap
      obj=ax.imshow(data,aspect='auto', **kwargs)

      #this is to block some cells for a particular purpose
      n=""
      for i in range(12):
      for j in range(27):
      if data[i,j]==-1:
      n="b"
      else : n=" "
      text = ax.text(j, i, n,ha="center", va="baseline", color="b")

      # Create colorbar
      cbar = ax.figure.colorbar(obj, ax=ax, **cbar_kw)
      cbar.ax.set_ylabel(cbarlabel, rotation=-90, va="bottom")
      ax.set_title("title")
      #fig.tight_layout()
      #fig.savefig("sample_plot.png",bbox_inches='tight',transparent=True)
      im=fig.canvas
      return im






      """
      def callback(instance):
      #heatmap(fig,ax,cmap="inferno_r", cbarlabel="density")
      #canvas = fig.canvas
      fig, ax = plt.subplots()
      heatmap(fig,ax,cmap="inferno_r", cbarlabel="density")
      self.im=FigureCanvasKivyAgg(plt.gcf())
      """



      class MatplotlibTest(App):
      title = 'Matplotlib Test'
      def refresh(self,instance):
      fig, ax = plt.subplots()
      heatmap(fig,ax,cmap="inferno_r", cbarlabel="density")
      plt.close('all')
      self.im=FigureCanvasKivyAgg(plt.gcf())

      def build(self):
      fig, ax = plt.subplots()
      heatmap(fig,ax,cmap="inferno_r", cbarlabel="density")
      self.im=FigureCanvasKivyAgg(plt.gcf())
      fl = BoxLayout(orientation="vertical")
      a = Button(text="refresh", height=40, size_hint_y=None)
      a.bind(on_release=self.refresh)

      fl.add_widget(self.im)

      fl.add_widget(a)
      return fl

      if __name__ == '__main__':
      MatplotlibTest().run()


      I'm trying to get this code to refresh and plot new data in the heatmap on realeasing the refresh button. But that's not happening. I'm unable to clear the plt.gcf() reference and load and plot a new one.



      I've tried all the plt.gcf().clear() , plt.close(), plt.Close('all'), plt.close('fig'), cleared axses and everything. Nothing works



      There is no .KV file for this one, its going to run as it is, but not going to be dynamically changing (which is the primary requirement).



      Also it would be extremely helpful if you could show me how to confine the plotting to one screen so i can move around multiple screens using kivy.uix.screenmanager.



      PS: I know there are many stupid mistakes here, and that is exactly why I'm here asking for help.



      All help is appreciated. :)







      python matplotlib kivy heatmap kivy-language






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Nov 8 at 6:13

























      asked Nov 7 at 13:43









      Soup_Battousai

      34




      34





























          active

          oldest

          votes











          Your Answer






          StackExchange.ifUsing("editor", function () {
          StackExchange.using("externalEditor", function () {
          StackExchange.using("snippets", function () {
          StackExchange.snippets.init();
          });
          });
          }, "code-snippets");

          StackExchange.ready(function() {
          var channelOptions = {
          tags: "".split(" "),
          id: "1"
          };
          initTagRenderer("".split(" "), "".split(" "), channelOptions);

          StackExchange.using("externalEditor", function() {
          // Have to fire editor after snippets, if snippets enabled
          if (StackExchange.settings.snippets.snippetsEnabled) {
          StackExchange.using("snippets", function() {
          createEditor();
          });
          }
          else {
          createEditor();
          }
          });

          function createEditor() {
          StackExchange.prepareEditor({
          heartbeatType: 'answer',
          convertImagesToLinks: true,
          noModals: true,
          showLowRepImageUploadWarning: true,
          reputationToPostImages: 10,
          bindNavPrevention: true,
          postfix: "",
          imageUploader: {
          brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
          contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
          allowUrls: true
          },
          onDemand: true,
          discardSelector: ".discard-answer"
          ,immediatelyShowMarkdownHelp:true
          });


          }
          });














           

          draft saved


          draft discarded


















          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53190665%2fmatplotlib-heatmap-in-a-kivy-window%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown






























          active

          oldest

          votes













          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes
















           

          draft saved


          draft discarded



















































           


          draft saved


          draft discarded














          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53190665%2fmatplotlib-heatmap-in-a-kivy-window%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown





















































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown

































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown







          這個網誌中的熱門文章

          Tangent Lines Diagram Along Smooth Curve

          Yusuf al-Mu'taman ibn Hud

          Zucchini