如何绘制两个字符串作为x轴值的图

时间:2017-08-11 09:51:11

标签: python matplotlib plot

我想使用matplotlib在一个图像中绘制两个图形。我想绘制的数据是:

x1 = ['sale','pseudo','test_mode']
y1 = [2374064, 515, 13]

x2 = ['ready','void']
y2 = [2373078, 1514]

我想在一张图片中绘制图形的条形图。我使用下面给出的代码:

f, (ax1, ax2) = plt.subplots(1, 2, sharey=True)
ax1.plot(x1, y1)
ax1.set_title('Two plots')
ax2.plot(x2, y2)

但是给出错误:

ValueError: could not convert string to float: PSEUDO

如何使用matplotlib在一个图像中绘制它们?

1 个答案:

答案 0 :(得分:0)

问题是您的x值不是数字,而是文本。相反,绘制y值,然后更改xticks的名称(请参阅此answer):

import matplotlib.pyplot as plt

x1 = ['sale','pseudo','test_mode']
y1 = [23, 51, 13]

x2 = ['ready','void']
y2 = [78, 1514]

f, axes = plt.subplots(1, 2, sharey=True)
for (x, y, ax) in zip((x1, x2), (y1, y2), axes):
    ax.plot(y)
    ax.set_xticks(range(len(x))) # make sure there is only 1 tick per value
    ax.set_xticklabels(x)
plt.show()

这会产生:

line graph

对于条形图,请使用ax.plot(y)切换ax.bar(range(len(x)), y)。这将产生以下结果:

bar graph