6

I've set up the following code to read in a .graphml file, preform a calculation (eigenvalues) and then plot the results. Here is the code I have so far:

import numpy as np
import networkx as nx
import matplotlib.pyplot as plt

# Read in the Data

G = nx.read_graphml("/home/user/DropBox_External_Datasets/JHU_Human_Brain/cat_brain_1.graphml")

nx.draw(G)
plt.savefig("test_graph.png")

Z = nx.to_numpy_matrix(G)

# Get Eigenvalues and Eigenvectors
# ----------------------------------------------------------------------------------
#
e_vals, e_vec = np.linalg.eigh(Z)

print("The eigenvalues of A are:", e_vals)
print("The size of the eigenvalues matrix is:", e_vals.shape)
# ----------------------------------------------------------------------------------

plt.plot(e_vals, 'g^')
plt.ylabel('Eigenvalues')
# plt.axis([-30, 300, -15, 30]) # Optimal settings for Rhesus data
# plt.axis([-0.07, 1, -0.2, 1.2])  # range to zoom in on cluster of points in Rhesus data

plt.grid(b=True, which='major', color='b', linestyle='-')
plt.show()

But no gridlines or axes show up on the graph. Is there something other then plt.grid() that I need to use?

dertkw
  • 7,798
  • 5
  • 37
  • 45
user3708902
  • 161
  • 1
  • 2
  • 12

1 Answers1

17

I have been finding that using the matplotlib object oriented API is a more robust way to make things work as expected. Pyplot is essentially a big wrapper for the object-oriented calls. I've written something that should be equivalent:

import matplotlib.pyplot as plt

# ... your other code here

# Using subplots
fig, ax = plt.subplots(ncols=1, nrows=1) # These arguments can be omitted for one
                                         # plot, I just include them for clarity
ax.plot(e_vals, 'g^')
ax.set_ylabel('Eigenvalues')

ax.grid(b=True, which='major', color='b', linestyle='-')

plt.show()
Trenton McKinney
  • 56,955
  • 33
  • 144
  • 158
Ajean
  • 5,528
  • 14
  • 46
  • 69
  • 3
    Calling `ax.grid (b=true)` instead of `ax.grid ()` was enough for me. [It seems to be the right way to use it](https://matplotlib.org/3.2.1/api/_as_gen/matplotlib.pyplot.grid.html): "*If any kwargs are supplied, it is assumed you want the grid on and b will be set to True. If b is None and there are no kwargs, this toggles the visibility of the lines.*" – mins Nov 13 '20 at 15:03
  • 1
    Also want to add that putting `ax.plot(...)` below `ax.grid(b=1)` will cover up the gridlines. As such, plot should be used before grid. – Potatoconomy Feb 10 '22 at 13:31