Plot string values in matplotlib
I am using matplotlib for a graphing application. I am trying to create a graph which has strings 开发者_StackOverflow社区as the X values. However, the using plot
function expects a numeric value for X.
How can I use string X values?
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()
Note that in order to preserve the order of the input strings on the plot you need to use matplotlib >=2.2.
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()
Why not just make the x value some auto-incrementing number and then change the label?
--jed
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).
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.
精彩评论