logo
down
shadow

matplotlib for loop to show, save and redraw all plots


matplotlib for loop to show, save and redraw all plots

By : Tushar Sarma
Date : November 17 2020, 01:00 AM
it helps some times Here's my python code, , You should write your self a helper function:
code :
def my_plotter(ax, t, z, est_z):
    ln1 = ax.plot(t, z, 'bo-', label='sample data')
    ln2 = ax.plot(t, est_z, 'go-', label='estimated sample data')
    ax.xlabel('time')
    ax.ylabel('data value')
    ax.grid(True)
    ax.legend()
    return ln1 + ln2

for i in xrange(2):
    # get the data
    t = a[i+1:(i+1)*60, 2]
    z = a[i+1:(i+1)*60, 3]
    est_z = a[i+1:(i+1)*60, 6]
    # make the figure
    fig, ax = plt.subplots()
    # do the plot
    my_plotter(ax, t, z, est_Z)
    # save
    fig.savefig('test_{}.png'.format(i))
# make one figure with 2 axes
fig, ax_lst = plt.subplots(1, 2)

for i, ax in zip(xrange(2), ax_lst):
    # get the data
    t = a[i+1:(i+1)*60, 2]
    z = a[i+1:(i+1)*60, 3]
    est_z = a[i+1:(i+1)*60, 6]
    # do the plot
    my_plotter(ax, t, z, est_Z)
# save the figure with both plots
fig.savefig('both.png')


Share : facebook icon twitter icon
How to show matplotlib plots in python

How to show matplotlib plots in python


By : user3913076
Date : March 29 2020, 07:55 AM
this one helps. I am sure the configuration of matplotlib for python is correct since I have used it to plot some figures. , In matplotlib you have two main options:
code :
import matplotlib.pyplot as plt

plt.plot(x, y)
plt.plot(z, t)
plt.show()
import matplotlib.pyplot as plt
from matplotlib import interactive
interactive(True)

plt.plot(x, y)
raw_input('press return to continue')

plt.plot(z, t)
raw_input('press return to end')
Plots are not visible using matplotlib plt.show()

Plots are not visible using matplotlib plt.show()


By : Baljit Singh
Date : March 29 2020, 07:55 AM
To fix this issue I'm really new in Python and Linux and I need help, I tried to use matplotlib for showing a simple plot in the following way: , As you can see:
code :
"The Gtk3Agg backend is known to not work on Python 3.x with pycairo."
Try installing cairocffi.
pip install cairocffi
sudo apt-get install python3-dev
sudo apt-get install libffi-dev
Matplotlib doesn't show plots on Mac; plt.show() hangs on 'MacOSX' backend

Matplotlib doesn't show plots on Mac; plt.show() hangs on 'MacOSX' backend


By : George Carey
Date : March 29 2020, 07:55 AM
will be helpful for those in need The answer, as pointed out by @ImportanceOfBeingErnest is that the backend configuration for me wasn't working. I'm not sure if I need to install some additional libraries or not. I decided not to use the MacOSX backend and used the Qt5Agg backend. This worked just fine and I didn't have to install any new libraries.
Python: matplotlib - loop, clear and show different plots over the same figure

Python: matplotlib - loop, clear and show different plots over the same figure


By : DAVINCII
Date : March 29 2020, 07:55 AM
With these it helps There are essentially two different ways to create animations in matplotlib
interactive mode
code :
import matplotlib.pyplot as plt

x = [1,1]
y = [1,2]

fig, (ax1,ax2) = plt.subplots(nrows=2, sharex=True, sharey=True)
line1, = ax1.plot(x)
line2, = ax2.plot(y)
ax1.set_xlim(-1,17)
ax1.set_ylim(-400,3000)
plt.ion()

for i in range(15):
    x.append(x[-1]+x[-2])
    line1.set_data(range(len(x)), x)
    y.append(y[-1]+y[-2])
    line2.set_data(range(len(y)), y)

    plt.pause(0.1)

plt.ioff()    
plt.show()
import matplotlib.pyplot as plt
import matplotlib.animation

x = [1,1]
y = [1,2]

fig, (ax1,ax2) = plt.subplots(nrows=2, sharex=True, sharey=True)
line1, = ax1.plot(x)
line2, = ax2.plot(y)
ax1.set_xlim(-1,18)
ax1.set_ylim(-400,3000)


def update(i):
    x.append(x[-1]+x[-2])
    line1.set_data(range(len(x)), x)
    y.append(y[-1]+y[-2])
    line2.set_data(range(len(y)), y)

ani = matplotlib.animation.FuncAnimation(fig, update, frames=14, repeat=False)   
plt.show()
import matplotlib.pyplot as plt
import matplotlib.animation
import numpy as np

x = np.linspace(0,24*np.pi,512)
y = np.sin(x)

def fft(x):
    fft = np.abs(np.fft.rfft(x))
    return fft**2/(fft**2).max()

fig, (ax1,ax2) = plt.subplots(nrows=2)
line1, = ax1.plot(x,y)
line2, = ax2.plot(fft(y))
ax2.set_xlim(0,50)
ax2.set_ylim(0,1)

def update(i):
    y = np.sin((i+1)/30.*x)
    line1.set_data(x,y)
    y2 = fft(y)
    line2.set_data(range(len(y2)), y2)

ani = matplotlib.animation.FuncAnimation(fig, update, frames=60, repeat=True)  
plt.show()
How to effectively redraw multiple matplotlib plots with blit

How to effectively redraw multiple matplotlib plots with blit


By : user3047209
Date : March 29 2020, 07:55 AM
hope this fix your issue The problem is that the snapshot of the background is taken at a moment in time where the figure has not yet been shown on screen. At that point the figure is 10 by 10 inches large. Later, it is shown inside the QMainWindow and resized to fit into the widget.
Only once that has happened, it makes sense to take the background snapshot.
code :
import numpy as np
import sys

from matplotlib.backends.qt_compat import QtCore, QtWidgets
from matplotlib.backends.backend_qt5agg import (FigureCanvas, NavigationToolbar2QT as NavigationToolbar)
from matplotlib.figure import Figure


class ApplicationWindow(QtWidgets.QMainWindow):
    def __init__(self):
        super().__init__()
        self._main = QtWidgets.QWidget()
        self.setCentralWidget(self._main)
        layout = QtWidgets.QVBoxLayout(self._main)

        self.static_canvas = FigureCanvas(Figure(figsize=(10, 10)))
        layout.addWidget(self.static_canvas)
        layout.addWidget(NavigationToolbar(self.static_canvas, self))
        axes = self.static_canvas.figure.subplots(2, 1)
        self.ax1 = axes[0]
        self.ax2 = axes[1]
        self.ax1.cla()
        self.ax2.cla()

        button = QtWidgets.QPushButton('Click me!')
        button.clicked.connect(self.update_canvas_blit)
        layout.addWidget(button)
        # Fixing random state for reproducibility
        np.random.seed(19680801)

        # Create random data
        N = 50000
        x = np.random.rand(N)
        y = np.random.rand(N)

        self.ax1.scatter(x, y)
        self.points = self.ax1.scatter([],[], s=5, color='red')

        x = np.linspace(0, 1000, 100000)
        self.ax2.plot(x, np.sin(x))
        self.lines, = self.ax2.plot([],[], color='red')
        self.static_canvas.draw()

        self._later()


    def _later(self, evt=None):
        self.timer = self.static_canvas.new_timer(interval=1000)
        self.timer.single_shot = True
        self.timer.add_callback(self.update_background)
        self.timer.start()


    def update_background(self, evt=None):
        self.background1 = self.static_canvas.copy_from_bbox(self.ax1.bbox)
        self.background2 = self.static_canvas.copy_from_bbox(self.ax2.bbox)

    def update_canvas_blit(self):
        N = 50
        x = np.random.rand(N)
        y = np.random.rand(N)

        self.static_canvas.restore_region(self.background1)
        self.points.set_offsets(np.c_[x,y])
        self.ax1.draw_artist(self.points)
        self.ax1.figure.canvas.blit(self.ax1.bbox)

        self.static_canvas.restore_region(self.background2)
        x = np.linspace(0, np.random.randint(500,1000), 1000)
        self.lines.set_data(x, np.sin(x))
        self.ax2.draw_artist(self.lines)
        self.ax2.figure.canvas.blit(self.ax2.bbox)

if __name__ == "__main__":
    qapp = QtWidgets.QApplication(sys.argv)
    app = ApplicationWindow()
    app.show()
    qapp.exec_()
Related Posts Related Posts :
  • Read data with NAs into python and calculate mean row-wise
  • How to print telnet response line by line?
  • Pylint: Avoid checking INSIDE DOCSTRINGS (global directive / rcfile)
  • Sending MIDI messages using Python (on Ubuntu)
  • Generate Dictionary in Python at run time
  • code is cluttered by try-except in Python
  • Python class inheritance - spooky action
  • Why is a Python multiprocessing daemon process not printing to standard output?
  • How to feed numeric data into a classifier?
  • How to unambiguously identify a Model as a lowercase string in Django
  • How to get only one specific line from subprocess output
  • Python network communication with encryption and password protection
  • with urllib urlopen read function but get none
  • django could not find database in ubuntu
  • How to replace a character in a string with a non ascii character in python?
  • Self learning data evaluation in Python
  • Django: UnicodeDecodeError while trying to read template 500.html
  • how can you Import an os variable into PYTHON and have it update?
  • Browse Folders to open a file in python
  • sql select group by a having count(1) > 1 equivalent in python pandas?
  • Why Insert command when button clicked OpenERP
  • Pandas dataframe from nested dictionary to melted data frame
  • Which is more efficient in Python: list.index() or dict.get()
  • Xor bits in python
  • A simple python confusion about format string
  • Finding index of a list containing an item, also in a list
  • How to test Domain is it 'www' domain or subdomain or name server domain or mail domain in python?
  • Keydown event for Pygame
  • Lazy loading csv with pandas
  • Use webdriver,python,beautifulsoup to retrieve dynamic website
  • Scrapy is Visiting same Url despite dont_filter=False
  • How to add support for SNI in python 2.7
  • Pandas: np.where with multiple conditions on dataframes
  • How to get meaningful words by splitting a continuous string?
  • TypeError: 'numpy.ndarray' object is not callable while extracting index and elements are stored in different array in p
  • Python: comparing list to a string
  • Is there any way to write '\r' into a file on linux with python?
  • matplotlib retrieve color from plt.plot command
  • Scrapy JSON export issues
  • beautifulsoup to retrieve the date
  • Django Rest Framework 3.0: Saving Nested, Many-To-One Relationship
  • Lost connection to MySQL server during Python connection
  • uploadede file path django
  • How to reduce a data with the longest string under pandas framework?
  • Single line for-loop to build a dictionary?
  • How to read in lines until a certain line?
  • Beautifulsoup to retrieve the href list
  • Python - Vincenty's inverse formula not converging (Finding distance between points on Earth)
  • Saving django model instance into another model
  • Same URL request fails with python->urllib but not with curl
  • Python dictionary: set value as the key string
  • With setuptools, when does namespace packages __init__.py files disappears?
  • Paraview: NameError: name 'inputs' is not defined
  • Too many values to unpack during template rendering
  • A different type of iterative function
  • Test if value exists in several lists
  • Go and Python HMAC libraries give different results
  • Python Nested Loop Working Weirdly
  • Why is this not assigning the correct value?
  • 'numpy.ndarray' object is not callable
  • shadow
    Privacy Policy - Terms - Contact Us © ourworld-yourmove.org