1

I just ran into an issue when I realized that I was plotting string data and my plots were not reflecting the data I was dealing with. It appears that matplotlib.pyplot does not produce an error when it is passed a string value and goes ahead and plots something but what exactly is it plotting? It shows numbers for the scale bar but they are simply the list of string values with no respect to numerical relationships. How does it decide where to plot the points?

Here is a code snippet to illustrate my question and a plot below.

import matplotlib.pyplot as plt

# Define data arrays
x = range(10)
data = [4.73, 5.01, 5.29, 6.75, 4.48, 4.49, 5.44, 5.53, 4.89, 4.59]
strData = ['4.73', '5.01', '5.29', '6.75', '4.48', '4.49', '5.44', '5.53', '4.89', '4.59']

# Open figure for plotting
fig = plt.figure()

# Define axis for plotting
ax1 = fig.add_subplot(111)
ax2 = ax1.twinx()

# Plot data
lns1 = ax1.plot(x, data, '-r', label = 'Float')
# Plot string data  
lns2 = ax2.plot(x, strData, 'ob', label = 'String')

# Compile labels
lns = lns1+lns2
labs = [l.get_label() for l in lns]

# Plot the legend
fig.legend(lns, labs, loc='upper right', fontsize= 9, prop={'size':9}, numpoints=1, framealpha=1)

# Show figure
plt.show()

enter image description here

1 Answer 1

1

As you can see, it will use the strings in the order you provided them, meaning the str with the lowest index will be plotted first, then the next at index 1 (as you can see on the second y-axis, where 4.73 is followed by 5.01 and 5.29. The distance between each value is simply one, as matplotlib has no concept for sorting strings.

You can see that if you use a range instead of your list of strings:

strData = list(range(10))
ax2.set_yticks(strData)

it will produce the same result: enter image description here

Sign up to request clarification or add additional context in comments.

Comments

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.