简体   繁体   中英

Why is matplotlib figure painted with colorbar colors?

I am trying to plot scatter-plot embedded to tkinter and update it with a for loop. I am able to update my plot; however, when my program initialize the plot, some part of the figure is covered by the colorbar color. Here is my code:

import matplotlib as mtpl
import matplotlib.pyplot as plt
import numpy as np
import tkinter as tk
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
from mpl_toolkits.axes_grid1 import make_axes_locatable
mtpl.use("TkAgg")

class RealTime(object):

def __init__(self, master):

    self.master = master
    self.lf = tk.LabelFrame(self.master, text="Plot")
    self.lf.grid(row=0, column=0, padx=3, pady=3)

    plt.ion()
    self.fig = plt.Figure()
    self.axis = self.fig.add_subplot(111)

    data = np.arange(2, 0, -0.1).reshape(5, 4)
    divider = make_axes_locatable(self.axis)
    self.cax = divider.append_axes('right', size='3%', pad=0.4, add_to_figure=True)
    im = self.axis.imshow(data, cmap="GnBu")
    self.fig.colorbar(im, cax=self.cax, orientation='vertical')

    self.axis.set_xlim(-1, 1)
    self.axis.set_ylim(-1.65, 1.65)
    self.axis.set_xlabel('Y-Direction')
    self.axis.set_ylabel('X-Direction')
    self.axis.set_title("Real Time Position")
    self.canvas = FigureCanvasTkAgg(self.fig, master=self.lf)
    self.canvas.get_tk_widget().grid(row=0, column=0, padx=3, pady=3)
    self.canvas.draw()
    self.master.protocol("WM_DELETE_WINDOW", self.on_closing)


def plot(self, data):
    s = self.axis.scatter(data[:, 0], data[:, 1], s=10, c=data[:, 2], cmap=plt.get_cmap("GnBu"), vmin=0, vmax=2)
    self.axis.legend(['Position'])
    self.fig.canvas.draw()
    self.fig.canvas.flush_events()

My program outputs this: 在此处输入图片说明

Do you know my figure is painted with colorbar colors ? Best Regards

SOLUTION Adding a self.axis.cla() after adding a colorbar solves the problem. But I stil don't understand why i was having such behaviour before?

In the line

im = self.axis.imshow(data, cmap="GnBu")

you plot an image to the axes. This image is what is shown in the axes and is probably desired. If you remove the lines

self.axis.set_xlim(-1, 1)
self.axis.set_ylim(-1.65, 1.65)

The result will look like

在此处输入图片说明

which is the complete image shown in the axes.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM