This question already has answers here:
use format with tex fraction expression in matplotlib python
(2 answers)
Interference between string formatting and LaTeX functions
(1 answer)
How to display a matrix in the Matplotlib annotations
(1 answer)
Closed 4 years ago.
I have some problem about .format() when I use it in matplotlib plotting: Suppose, I have a matrix A = np.column_stack([[0, 1], [-1, 0]]) and I have to display this matrix in my plot. Also this matrix may be changed as per my need. So I use the following code but it gives error. Can you please tell me how to do this task. Also I faced a similar problem when I try to display a vector like, $2\hat{i}+5 \hat{j}$:
I try the following for the matrix:
A = np.column_stack([[0, 1], [-1, 0]])
matrix = r'$\left( \begin{array}{ll} {a11} & {a12} \\ {a21} & {a22} \end{array} \right)$'.format(a11=A[0][0], a12=A[0][1], a21=A[1][0], a22=A[1][1])
plt.title(matrix)
Output:
---------------------------------------------------------------------------
KeyError Traceback (most recent call last)
<ipython-input-89-12cfe5180092> in <module>()
12
13 A = np.column_stack([[0, 1], [-1, 0]]) #Matrix
---> 14 title = r'$\left( \begin{array}{ll} {a11} & {a12} \\ {a21} & {a22} \end{array} \right)$'.format(a11=A[0][0], a12=A[0][1], a21=A[1][0], a22=A[1][1])
15
16 #Plotting:
KeyError: 'array'
I try the following for the vector:
x = [2,3]
plt.text(2,3,'${a}\hat{i}+{b}\hat{j}$'.format(a= x[0], b=x[1]))
Output:
---------------------------------------------------------------------------
KeyError Traceback (most recent call last)
<ipython-input-92-31281b09369d> in <module>()
32
33
---> 34 plt.text(2,3,'${a}\hat{i}+{b}\hat{j}$'.format(a= x[0], b=x[1]))
35
36 #plt.title(title, y = 1.03)
KeyError: 'i'
I've used your second example to provide an answer for simplicity to explain the issue.
x = [2,3]
plt.text(2,3,'${a}\hat{i}+{b}\hat{j}$'.format(a= x[0], b=x[1]))
This returns a KeyError: 'i' because the array variable specified in the string as {i} has not been set in your .format() statement. It was also fail if you just add i to your .format() statement as j has not been specified either.
See the following for a working example:
x = [2,3]
plt.text(2,3,'${a}\hat{i}+{b}\hat{j}$'.format(a= x[0], b=x[1], i="SOMETHING", j="SOMETHING"))
SUMMARY: Everything inside a {} needs to be set in your .format() statement.
Related
I was trying to construct a one-hot encoding system by using Python 3.7 + Jupyter notebook, and I ran into an error like this:
TypeError Traceback (most recent call last)
<ipython-input-87-0fc633482cfd> in <module>
1 for i, sample in enumerate(samples):
----> 2 for j, word in list(enumerate(sample.split()))[:max_length]:
3 index = all_token_index.get(word)
4 result[i,j,index] = 1
TypeError: 'list' object is not callable
Here are the original code:
import numpy as np
samples = ['This is a dog','This is a cat']
all_token_index = {}
for sample in samples:
for word in sample.split():
if word not in all_token_index:
all_token_index[word] = len(all_token_index) + 1
max_length = 10
result = np.zeros(shape=(len(samples), max_length, max(all_token_index.values()) + 1 ))
for i, sample in enumerate(samples):
# Get keys and values in sample
for j, word in list(enumerate(sample.split()))[:max_length]:
index = all_token_index.get(word)
result[i,j,index] = 1
Could you please help me? Thanks in advance!
The correct answer was given by #Samwise and #Ronald in the comments. Like they said, I used a list variable in one deleted notebook cell. After restarting the notebook, the problem was fixed.
I'm having problems storing the out put of numpy.linalg.eig(). I want to store then into two different array. This is the way I've tried:
vec1 = np.zeros(y.shape[0],dtype=complex)
vec2 = np.zeros(y.shape[0],dtype=complex)
for i in np.arange(y.shape[0]):
val,vec= np.linalg.eig(rho_t[:,:,i])
vec1[i] = vec[0]
vec2[i] = vec[1]
The ERROR message is the following:
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-389-791a7e5e4801> in <module>
3 for i in np.arange(y.shape[0]):
4 val,vec= np.linalg.eig(rho_t[:,:,i])
----> 5 vec1[i] = vec[0]
6 vec2[i] = vec[1]
7 #vec2[i] = np.array(sol[1][1])
TypeError: only length-1 arrays can be converted to Python scalars
No idea what is the problem, can somebody help me please
According to documentation: https://docs.scipy.org/doc/numpy/reference/generated/numpy.linalg.eig.html
The normalized (unit “length”) eigenvectors, such that the column
v[:,i] is the eigenvector corresponding to the eigenvalue w[i].
so perhaps the solution is this:
for i in np.arange(y.shape[0]):
val,vec= np.linalg.eig(rho_t[:,:,i])
vec1[i] = vec[:,0]
vec2[i] = vec[:,1]
I'm plotting a function over a range of values, so naturally I fed a numpy.arange() into the function to get the dependent values for the plot. However, some of the values are going to NaN or infinity. I know why this is happening, so I went back into the function and included some conditionals. If they were working, these would replace values leading to the NaN outputs only when conditions are met. However, based on the errors I'm getting back, it appears the operations are being performed on every entry in the inputs, rather than only when those conditions are met.
My code is as follows
import matplotlib.pyplot as plt
import numpy as np
import math
k=10
l=50
pForPlot = np.arange(0,1,0.01)
def ProbThingHappens(p,k,l):
temp1 = (((1-p)**(k-1)*((k-1)*p+1))**l)
temp2 = (((1-p)**(1-k))/((k-1)*p+1))
if float(temp2) <= 1.0*10^-300:
temp2 = 0
print("Temp1 = " + str(temp1))
print("Temp2 = " + str(temp2))
temp = temp1*(temp2**l-1)
if math.isnan(temp):
temp = 1
print("Temp = " + str(temp))
return temp
plt.plot(pForPlot,ProbThingHappens(pForPlot,k,l))
plt.axis([0,1,0,1])
plt.xlabel("p")
plt.ylabel("Probability of thing happening")
plt.rcParams["figure.figsize"] = (20,20)
plt.rcParams["font.size"] = (20)
plt.show()
And the error it returns is:
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-20-e707ad24af01> in <module>
20 return temp
21
---> 22 plt.plot(pForPlot,ProbAnyOverlapsAtAll(pForPlot,k,l))
23 plt.axis([0,1,0,0.01])
24 plt.xlabel("p")
<ipython-input-20-e707ad24af01> in ProbAnyOverlapsAtAll(p, k, l)
10 temp1 = (((1-p)**(k-1)*((k-1)*p+1))**l)
11 temp2 = (((1-p)**(1-k))/((k-1)*p+1))
---> 12 if float(temp2) <= 1.0*10^-300:
13 temp2 = 0
14 print("Temp1 = " + str(temp1))
TypeError: only size-1 arrays can be converted to Python scalars
How do I specify within the function that I only want to operate on specific values, rather than the whole array of values being produced? I assume that if I know how to get float() to pick out just one value, it should be straightforward to do the same for other conditionals. I'm terribly sorry if this question has been asked before, but I searched for answers using every phrasing I could imagine. I'm afraid in this case I may simply not know know the proper terminology. Any assistance would be greatly appreciated.
def profits(q):
range_price = range_p(q)
range_profits = [(x-c(q))*demand(q,x) for x in range_price]
price = range_price[argmax(range_profits)] # recall from above that argmax(V) gives
# the position of the greatest element in a vector V
# further V[i] the element in position i of vector V
return (price-c(q))*demand(q,price)
print profits(0.6)
print profits(0.8)
print profits(1)
0.18
0.2
0.208333333333
With q (being quality) in [0,1], we know that the maximizing quality is 1. Now the question is, how can I solve such an equation? I keep getting the error that either q is not defined yet (which is only natural as we are looking for it) or I get the error that some of the arguments are wrong.
q_firm = optimize.fminbound(-profits(q),0,1)
This is what I've tried, but I get this error:
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
<ipython-input-99-b0a80dc20a3d> in <module>()
----> 1 q_firm = optimize.fminbound(-profits(q),0,1)
NameError: name 'q' is not defined
Can someone help me out? If I need to supply you guys with more information to the question let me know, it's my first time using this platform. Thanks in advance!
fminbound needs a callable, while profits(q) tries to calculate a single value. Use
fminbound(lambda q: -profits(q), 0, 1)
Note that the lambda above is only needed to generate a function for negative profits. Better define a function for -profits and feed it to fminbound.
Better still, use minimize_scalar instead of fminbound.
I have written a code in python to generate a sequence of ARIMA model's and determine their AIC values to compare them.The code is as below,
p=0
q=0
d=0
for p in range(5):
for d in range(1):
for q in range(4):
arima_mod=sm.tsa.ARIMA(df,(p,d,q)).fit()
print(arima_mod.params)
print arima_mod.aic()
I am getting a error message as below,
TypeError Traceback (most recent call last)
<ipython-input-60-b662b0c42796> in <module>()
8 arima_mod=sm.tsa.ARIMA(df,(p,d,q)).fit()
9 print(arima_mod.params)
---> 10 print arima_mod.aic()
global arima_mod.aic = 1262.2449736558815
11
**TypeError: 'numpy.float64' object is not callable**
Remove the brackets after print arima_mod.aic(). As I read it, arima_mod.aic is 1262.2449736558815, and thus a float. The brackets make python think it is a function, and tries to call it. You do not want that (because it breaks), you just want that value. So remove the brackets, and you'll be fine.