logo
down
shadow

Embedding several inset axes in another axis using matplotlib


Embedding several inset axes in another axis using matplotlib

By : user2951675
Date : November 18 2020, 11:13 AM
I wish this help you As @hitzg mentioned, the most common way to accomplish something like this is to use GridSpec. GridSpec creates an imaginary grid object that you can slice to produce subplots. It's an easy way to align fairly complex layouts that you want to follow a regular grid.
However, it may not be immediately obvious how to use it in this case. You'll need to create a GridSpec with numrows * numinsets rows by numcols columns and then create the "main" axes by slicing it with intervals of numinsets.
code :
import numpy as np
import matplotlib.pyplot as plt

def build_axes_with_insets(numrows, numcols, numinsets, **kwargs):
    """
    Makes a *numrows* x *numcols* grid of subplots with *numinsets* subplots
    embedded as "sub-rows" in the last column of each row.

    Returns a figure object and a *numrows* x *numcols* object ndarray where
    all but the last column consists of axes objects, and the last column is a
    *numinsets* length object ndarray of axes objects.
    """
    fig = plt.figure(**kwargs)
    gs = plt.GridSpec(numrows*numinsets, numcols)

    axes = np.empty([numrows, numcols], dtype=object)
    for i in range(numrows):
        # Add "main" axes...
        for j in range(numcols - 1):
            axes[i, j] = fig.add_subplot(gs[i*numinsets:(i+1)*numinsets, j])

        # Add inset axes...
        for k in range(numinsets):
            m = k + i * numinsets
            axes[i, -1][k] = fig.add_subplot(gs[m, -1])

    return fig, axes

def plot(axes):
    """Recursive plotting function just to put something on each axes."""
    for ax in axes.flat:
        data = np.random.normal(0, 1, 100).cumsum()
        try:
            ax.plot(data)
            ax.set(xticklabels=[], yticklabels=[])
        except AttributeError:
            plot(ax)

fig, axes = build_axes_with_insets(2, 4, 3, figsize=(12, 6))
plot(axes)
fig.tight_layout()
plt.show()


Share : facebook icon twitter icon
matplotlib: inset axes for multiple boxplots

matplotlib: inset axes for multiple boxplots


By : Sahil Awan
Date : March 29 2020, 07:55 AM
wish helps you The loc determines the location of the zoomed axis, 1 for upper right, 2 for upper left and so on. I modified the example code slightly to generate multiple zoomed axis.
code :
import matplotlib.pyplot as plt

from mpl_toolkits.axes_grid1.inset_locator import zoomed_inset_axes
from mpl_toolkits.axes_grid1.inset_locator import mark_inset

import numpy as np

def get_demo_image():
    from matplotlib.cbook import get_sample_data
    import numpy as np
    f = get_sample_data("axes_grid/bivariate_normal.npy", asfileobj=False)
    z = np.load(f)
    # z is a numpy array of 15x15
    return z, (-3,4,-4,3)


fig = plt.figure(1, [5,4])
ax = fig.add_subplot(111)

# prepare the demo image
Z, extent = get_demo_image()
Z2 = np.zeros([150, 150], dtype="d")
ny, nx = Z.shape
Z2[30:30+ny, 30:30+nx] = Z

# extent = [-3, 4, -4, 3]
ax.imshow(Z2, extent=extent, interpolation="nearest",
          origin="lower")

axins = zoomed_inset_axes(ax, 6, loc=1) # zoom = 6
axins.imshow(Z2, extent=extent, interpolation="nearest",
             origin="lower")

# sub region of the original image
x1, x2, y1, y2 = -1.5, -0.9, -2.5, -1.9
axins.set_xlim(x1, x2)
axins.set_ylim(y1, y2)

axins1 = zoomed_inset_axes(ax, 8, loc=2) # zoom = 6
axins1.imshow(Z2, extent=extent, interpolation="nearest",
             origin="lower")

# sub region of the original image
x1, x2, y1, y2 = -1.2, -0.9, -2.2, -1.9
axins1.set_xlim(x1, x2)
axins1.set_ylim(y1, y2)

plt.xticks(visible=False)
plt.yticks(visible=False)

# draw a bbox of the region of the inset axes in the parent axes and
# connecting lines between the bbox and the inset axes area
mark_inset(ax, axins, loc1=2, loc2=4, fc="none", ec="0.5")
mark_inset(ax, axins1, loc1=2, loc2=4, fc="none", ec="0.5")

plt.draw()
plt.show()
from pylab import *
from mpl_toolkits.axes_grid1.inset_locator import zoomed_inset_axes
from mpl_toolkits.axes_grid1.inset_locator import mark_inset

# fake up some data
spread= rand(50) * 100 
center = ones(25) * 50
flier_high = rand(10) * 100 + 100
flier_low = rand(10) * -100
data =concatenate((spread, center, flier_high, flier_low), 0)

# fake up some more data
spread= rand(50) * 100
center = ones(25) * 40
flier_high = rand(10) * 100 + 100
flier_low = rand(10) * -100
d2 = concatenate( (spread, center, flier_high, flier_low), 0 )
data.shape = (-1, 1)
d2.shape = (-1, 1)
data = [data, d2, d2[::2,0]]

# multiple box plots on one figure
fig = plt.figure(1, [5,4])
ax = fig.add_subplot(111)
ax.boxplot(data)
ax.set_xlim(0.5,5)
ax.set_ylim(0,300)

# Create the zoomed axes
axins = zoomed_inset_axes(ax, 3, loc=1) # zoom = 3, location = 1 (upper right)
axins.boxplot(data)

# sub region of the original image
x1, x2, y1, y2 = 0.9, 1.1, 125, 175
axins.set_xlim(x1, x2)
axins.set_ylim(y1, y2)
plt.xticks(visible=False)
plt.yticks(visible=False)

# draw a bbox of the region of the inset axes in the parent axes and
# connecting lines between the bbox and the inset axes area
mark_inset(ax, axins, loc1=2, loc2=4, fc="none", ec="0.5")

show() 
from pylab import *

# fake up some data
spread= rand(50) * 1
center = ones(25) * .5
flier_high = rand(10) * 100 + 100
flier_low = rand(10) * -100
data =concatenate((spread, center, flier_high, flier_low), 0)

# fake up some more data
spread= rand(50) * 1
center = ones(25) * .4
flier_high = rand(10) * 100 + 100
flier_low = rand(10) * -100
d2 = concatenate( (spread, center, flier_high, flier_low), 0 )
data.shape = (-1, 1)
d2.shape = (-1, 1)
data = [data, d2, d2[::2,0]]

# multiple box plots on one figure
fig = plt.figure(1, [5,4]) # Figure Size
ax = fig.add_subplot(111)  # Only 1 subplot 
ax.boxplot(data)
ax.set_xlim(0.5,5)
ax.set_ylim(.1,300)
ax.set_yscale('log')

show()
Adding a second Y-Axis to an inset zoom axes

Adding a second Y-Axis to an inset zoom axes


By : Kevin
Date : March 29 2020, 07:55 AM
I hope this helps you . So I found the answer to my question... Sorry for the delay, but I put this issue on hold... I did find the bug but just a workaround by generating an another zoom inset, using the alpha canal and disabling a lot of stuff...
Here is my code:
code :
import numpy,os,sys
import pylab
from mpl_toolkits.axes_grid1.inset_locator import zoomed_inset_axes
from mpl_toolkits.axes_grid1.inset_locator import mark_inset

# Initializing the curve
fig_cal=pylab.figure()
host_weight = fig_cal.add_subplot(111)
host_mass = host_weight.twinx()
Tension = numpy.linspace(0,0.08,100)
Weight = 0.5* Tension
Mass = Weight/9.81

# Plotting the curve
host_weight.plot(Tension, Weight, 'r', label='Fitted line',lw=2)
host_mass.plot(Tension, Mass, alpha=0)

# Cosmetic on the Figure
host_weight.set_xlabel("Tension U [$V$]")
host_weight.set_ylabel("Weight F [$N$]")
host_mass.set_ylabel("Mass M [$kg$]")
host_mass.set_ylim(host_weight.axis()[-2]/9.81, host_weight.axis()[-1]/9.81)
host_weight.grid(False)

# Zoom on the first measurement
zoom_weight = zoomed_inset_axes(host_weight, zoom = 7.5, bbox_to_anchor=(0.95,0.5), bbox_transform=host_weight.transAxes)
zoom_weight.plot(Tension[:4], Weight[:4], 'r', lw=2)
zoom_weight.set_xticks(zoom_weight.xaxis.get_majorticklocs()[::2])
zoom_weight.set_yticks(zoom_weight.yaxis.get_majorticklocs()[::2])
zoom_mass = zoomed_inset_axes(host_mass, zoom = 7.5, bbox_to_anchor=(0.95,0.5),     bbox_transform=host_mass.transAxes)
zoom_mass.xaxis.set_visible(False)
zoom_mass.spines['left'].set_visible(False)
zoom_mass.spines['top'].set_visible(False)
zoom_mass.patch.set_alpha(00)
zoom_mass.yaxis.tick_right()
zoom_mass.yaxis.set_label_position('right')
zoom_mass.yaxis.set_offset_position('right')
zoom_mass.plot(Tension[:4], Mass[:4],color='w', alpha=0)
zoom_mass.set_ylim(zoom_weight.axis()[-2]/9.81,zoom_weight.axis()[-1]/9.81)

pylab.show()
matplotlib axes.clear() of twinx axes does not clear second y-axis label

matplotlib axes.clear() of twinx axes does not clear second y-axis label


By : Prithu1310
Date : March 29 2020, 07:55 AM
I wish did fix the issue. The problem is caused by your second ax_hist = ax.twinx() which creates a second twin axis of the first ax. You only need to create the twin axis once.
code :
import matplotlib.pyplot as plt
import numpy as np

fig, ax = plt.subplots()

d1 = np.random.random(100)
d2 = np.random.random(1000)

ax_hist = ax.twinx() # Create the twin axis, only once

ax.plot(d1)
ax_hist.hist(d1)

ax.clear()
ax_hist.clear()

ax.plot(d2)
ax_hist.hist(d2)
Matplotlib.pyplot - Deactivate axes in figure. /Axis of figure overlap with axes of subplot

Matplotlib.pyplot - Deactivate axes in figure. /Axis of figure overlap with axes of subplot


By : bladeee
Date : March 29 2020, 07:55 AM
I hope this helps you . , If you want to remove the axes completely, you should try:
code :
plt.axis('off')
cur_axes = plt.gca()
cur_axes.axes.get_xaxis().set_visible(False)
cur_axes.axes.get_yaxis().set_visible(False)
matplotlib.pyplot: sharing axes' x-axis after plotting doesn't put them on the same x-axis limits

matplotlib.pyplot: sharing axes' x-axis after plotting doesn't put them on the same x-axis limits


By : saleema
Date : March 29 2020, 07:55 AM
this one helps. ax.get_shared_x_axes().join(ax, ax2) just appends ax2 to the Grouper. You still need to autoscale the axes
code :
ax.autoscale()
Related Posts Related Posts :
  • Return new instance of subclass when using methods inherited from parent class in Python
  • Which function in django.contrib.auth creates the default model permissions?
  • Formatting text in tabular form with Python
  • How to determine the first day of a month in Python
  • Error while converting date to timestamp in python
  • Python string iterations
  • Is there any file number limitation when you select multiple files with wxFileDialog?
  • Errors with Matplotlib when making an executable with Py2exe (Python)
  • Django Haystack - Indexing single field
  • Go Pro Hero 3 - Streaming video over wifi
  • Appending a column in .csv with Python/Pandas
  • How to change my result directory in Robot framework using RIDE?
  • problem with using pandas to manipulate a big text file in python
  • python-magic module' object has no attribute 'open'
  • Where goes wrong for this High Pass Filter in Python?
  • Why inserting keys in order into a python dict is faster than doint it unordered
  • flann index saving in python
  • Create new instance of list or dictionary without class
  • How can I easily convert FORTRAN code to Python code (real code, not wrappers)
  • Address of lambda function in python
  • Python adding space between characters in string. Most efficient way
  • python http server, multiple simultaneous requests
  • Disguising username & password on distributed python scripts
  • Post GraphQL mutation with Python Requests
  • Why doesnt pandas create an excel file?
  • Rolling comparison between a value and a past window, with percentile/quantile
  • How to avoid repetitive code when defining a new type in python with signature verification
  • How to configure uWSGI in order to debug with pdb (--honour-stdin configuration issue)
  • In Python, how do you execute objects that are functions from a list?
  • Python- Variable Won't Subtract?
  • Processing Power In Python
  • Python 2.7.2 - Cannot import name _random or random from sys
  • Why doesn't the Python sorted function take keyword order instead of reverse?
  • Make a function redirect to other functions depending on a variable
  • get_absolute_url in django-categories
  • Monitoring non-Celery background task with New Relic in Python
  • Feature selection with LinearSVC
  • LSTM - Predicting the same constant values after a while
  • Test the length of elements in a list
  • Django: render radiobutton with 3 columns, cost column must change according to size & quantity selected
  • Python class attributes vs global variable
  • sys.stdout.writelines("hello") and sys.stdout.write("hello")
  • is ndarray faster than recarray access?
  • Python - search through directory trees, rename certain files
  • GAE: How to build a query where a string begins with a value
  • TypeError: __init__() takes at least 2 arguments (1 given)
  • Overriding and customizing "django.contrib.auth.views.login"
  • Django : Redirect to a particular page after login
  • Python search and copy files in directory
  • pretty printing numpy ndarrays using unicode characters
  • Frequent pattern mining in Python
  • How can I make a set of functions that can be used synchronously as well as asynchronously?
  • Convert one dice roll to two dice roll
  • count occourrence in a list
  • Writing an If condition to filter out the first word
  • to read file and compare column in python
  • Install python-numpy in the Virtualenv environment
  • `.select_by_visible_text()` is failed to select element?
  • Unable to send data multiple requests in a single connection — socket error
  • Pandas HDFStore unload dataframe from memory
  • shadow
    Privacy Policy - Terms - Contact Us © ourworld-yourmove.org