Matplotlib and Numpy: Log plot with high order numbers [duplicate]

+1 vote
asked Sep 12, 2017 by thomas-eckert

This question already has an answer here:

  • python+numpy: why does numpy.log throw an attribute error if its operand is too big? 2 answers

1 Answer

+1 vote
answered Mar 18, 2018 by cge

Python does automatic, weird things for integers larger than can be held as a 64-bit integer (on 64 bit systems), like 10**21. In doing so, numpy will then not automatically use a numpy dtype for such objects, instead using the object dtype. This, in turn, does not support ufuncs like np.log:

> np.log([10**3])
array([ 6.90775528])
> np.log([10**30])
AttributeError: 'int' object has no attribute 'log'

One easy solution here is to make sure that numpy converts n_pts, the array with the large numbers, into a dtype it can actually use, like float:

import matplotlib.pyplot as plt
import numpy as np
n_pts = np.array([10**21,10**19,10**23,10**11,10**15,10**14,10**17,10**6], dtype='float')
KT_pts = [10000,100,1000,0.05,2,0.1,0.2,0.01]
n_set = np.logspace(6,25)
debye_set = 7.43*np.logspace(-1,-7,10)
def energy(n,debye): return n*(debye/7430)**2
fig,ax=plt.subplots()
ax.scatter(n_pts,KT_pts)
for debye in debye_set: ax.loglog(n_set,energy(n_set,debye))
plt.show()

output

Welcome to Q&A, where you can ask questions and receive answers from other members of the community.
...