0

I am trying to convert some numbers represented as strings but I get an error!

Here is my code

import numpy as np
import matplotlib.pyplot as plt

a = np.linspace(-np.pi*2, np.pi*2, 200)
b = np.cos(a)

fig, ax = plt.subplots()

ax.plot(a, b)

fig.canvas.draw()

labels = [item.get_text() for item in ax.get_xticklabels()]

labels = [float(label) for label in labels]

float(labels[-1]) # this works

error : labels = [float(label) for label in labels] ValueError: could not convert string to float: '−8'

labels, in this case, can be generated as [str(i) for i in range(-8, 9, 2)] which I can convert its items to float but not the text of the label retrieved from matplotlib!

I believe the issue is with the - sign.

since when i check '-8' in labels gives False

but '8' in labels gives True

2 Answers 2

3

One solution is to replace the unicode character U+002D to U+2212. this answer can help you with that. But it also says that it's not very recomended. You can use instead ax.get_xticks()

print(ax.get_xticks())
output : [-8. -6. -4. -2.  0.  2.  4.  6.  8.]
Sign up to request clarification or add additional context in comments.

Comments

1

I believe the issue is with the - sign.

It is, sort of. The problem is that in the string that could not be converted, the character in front of the '8' is not an ASCII hyphen (with Unicode codepoint U+002D) but rather the Unicode character for a minus sign (with Unicode codepoint U+2212). Those characters look very similar, but Python only treats the first one as a minus sign.

2 Comments

do you have any idea how can I convert it to an understandable minus sign for python
@KhalilAlHooti The replace method for strings should do it, something like label.replace("\u2212", "-"). But I think Gabriel's answer is better.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.