Reputation: 367
Using matplotlib for Python, how do I write put 'sqrt(2)' with the square root symbol instead of its decimal value in a plot legend? See the plot and code below. Please let me know if I need to elaborate. Thank you!
import matplotlib.pyplot as plt
import numpy as np
E = np.linspace(50000,200000,1000) # eV
a = 3.615*10**(-10) #m
h = 6.582*10**(-16) #eV s
m = 9.109*10**(-31) #kg
J = 6.242*10**(-18) #1eV to J
def T(x,E):
return np.arcsin(x*np.sqrt(J*((np.pi**2 *h**2)/(a**2 * 4*m *E))))*1000
fig, ax = plt.subplots()
x = np.asarray([2*np.sqrt(2), 2, np.sqrt(3)])
for i in x:
ax.plot(E,T(i,E),label='hkl=%s' % i)
plt.ylabel('$\Theta$ (mrad)')
plt.xlabel('Energy (eV)')
plt.legend(bbox_to_anchor=(1.01, 1), loc=1, borderaxespad=0.)
The plot this spits out is:
EDIT:
I should mention that I want this code to take any value in x
and plot it, using an actual square root symbol in the legend instead of its decimal value.
Upvotes: 3
Views: 3360
Reputation: 645
You can use Unicode to write the square root symbol as a string and then add whatever number you are interested in. To write a square root symbol as a string, use '\u221A'
.
One way to modify your code would be to turn x into a dictionary. So x={'2\u221A2': 2*np.sqrt(2), '2':2, '\u221A3':np.sqrt(3)}
. Your for loop would become for k,v in x.items()
where k and v are short for key and value and the first line in the loop would be ax.plot(E,T(v,E),label='hkl=%s' % k)
In terms of parsing a number and writing it out as a square root, that's a little more involved and would look something like this question on code review: https://codereview.stackexchange.com/questions/144041/reduce-square-root-to-simplest-radical-form
Upvotes: 2