11

I am using matplotlib for a graphing application. I am trying to create a graph which has strings as the X values. However, the using plot function expects a numeric value for X.

How can I use string X values?

5 Answers 5

18

From matplotlib 2.1 on you can use strings in plotting functions.

import matplotlib.pyplot as plt
x = ["Apple", "Banana", "Cherry"]
y = [5,2,3]

plt.plot(x, y)

plt.show()

enter image description here

Note that in order to preserve the order of the input strings on the plot you need to use matplotlib >=2.2.

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

1 Comment

This was downvoted, but I upvoted it since it is by far the most compact solution and, in most cases, won't break anything else.
12

You should try xticks

import pylab

names = ['anne','barbara','cathy']
counts = [3230,2002,5456]

pylab.figure(1)
x = range(3)
pylab.xticks(x, names)
pylab.plot(x,counts,"g")

pylab.show()

Comments

4

Why not just make the x value some auto-incrementing number and then change the label?

--jed

Comments

1

Here's one way which i know works, though i would think creating custom symbols is a more natural way accomplish this.

from matplotlib import pyplot as PLT

# make up some data for this example
t = range(8)
s = 7 * t + 5
# make up some data labels which we want to appear in place of the symbols
x = 8 * "dp".split()
y = map(str, range(8))
data_labels = [ i+j for i, j in zip(x, y)]
fig = PLT.figure()
ax1 = fig.add_subplot(111)
ax1.plot(t, s, "o", mfc="#FFFFFF")     # set the symbol color so they are invisible
for a, b, c in zip(t, s, data_labels) :
    ax1.text(a, b, c, color="green")

PLT.show()

So this puts "dp1", "dp2",... in place of each of the original data symbols--in essence creating custom "text symbols" though again i have to believe there's a more direct way to do this in matplotlib (without using Artists).

1 Comment

Thank you for the reply. I found this: class matplotlib.ticker.FixedFormatter(seq), which lets you specify the set of strings as a sequence
0

I couldn't find a convenient way to accomplish that, so I resorted to this little helper function.

import matplotlib.pyplot as p
def plot_classes(x, y, plotfun=p.scatter, **kwargs):
    from itertools import count
    import numpy as np
    classes = sorted(set(x))
    class_dict = dict(zip(classes, count()))
    class_map = lambda x: class_dict[x]
    plotfun(map(class_map, x), y, **kwargs)
    p.xticks(np.arange(len(classes)), classes)

Then, calling plot_classes(data["class"], data["y"], marker="+") should work as expected.

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.