python-3.xmatplotlibgridaxesinsets

Changing the grid properties of insets in matplotlib


This is a follow up to my question posted here. A network diagram is added as an inset in matplotlib figure.

import networkx as nx
import matplotlib.pyplot as plt

G = nx.gnm_random_graph(n=10, m=15, seed=1)
nxpos = nx.spring_layout(G, dim=3, seed=1)

nxpts = [nxpos[pt] for pt in sorted(nxpos)]
nx_lines = [(nxpts[i], nxpts[j]) for i, j in G.edges()]

# node values
values = [[1, 0, 0, 0, 0, 0, 0, 0, 0, 0],
          [30, 80, 10, 79, 70, 60, 75, 78, 65, 10],
          [1, .30, .10, .79, .70, .60, .75, .78, .65, .90]]
time = [0.0, 0.1, 0.2]  # in seconds


fig, ax = plt.subplots()
ax.plot(
    [1, 2, 3], [1, 2, 3],
    'go-',
    label='line 1',
    linewidth=2
 )

from mpl_toolkits.mplot3d import (Axes3D)
from matplotlib.transforms import Bbox
rect = [.6, 0, .5, .5]
bbox = Bbox.from_bounds(*rect)
inax = fig.add_axes(bbox, projection = '3d')
  
# inax.axis('off')


# set angle
angle = 25
inax.view_init(10, angle)

# hide axes, make transparent
# inax.set_facecolor('none')
inax.grid('off')
import numpy as np

# plot 3d
seen = set()
for i, j in G.edges():
    x = np.stack((nxpos[i], nxpos[j]))
    inax.plot(*x.T, color = 'k')
    if i not in seen:
        inax.scatter(*x[0], color = 'skyblue')
        seen.add(i)
    if j not in seen:
        inax.scatter(*x[1], color = "skyblue")
        seen.add(j)

fig.show()

I would like to change the grid properties i.e set the grid color to red and change line width. I tried inax.grid('on', color='r') but this doesn't change the color. Suggestions on how to change the settings will be really helpful.


Solution

  • You can do it like this:

    inax.w_xaxis._axinfo.update({'grid' : {'color': 'red', 'linewidth': 0.8, 'linestyle': '-'}})
    inax.w_yaxis._axinfo.update({'grid' : {'color': 'red', 'linewidth': 0.8, 'linestyle': '-'}})
    inax.w_zaxis._axinfo.update({'grid' : {'color': 'red', 'linewidth': 0.8, 'linestyle': '-'}})
    

    Output: enter image description here