[英]How to plot two plots with strings as x axis values
I want to plot two figures in one image using matplotlib.我想使用 matplotlib 在一张图像中绘制两个数字。 Data which I want to plot is:
我要绘制的数据是:
x1 = ['sale','pseudo','test_mode']
y1 = [2374064, 515, 13]
x2 = ['ready','void']
y2 = [2373078, 1514]
I want to plot the bar plot for both the figure in one image.我想为一个图像中的两个图形绘制条形图。 I used the code given below:
我使用了下面给出的代码:
f, (ax1, ax2) = plt.subplots(1, 2, sharey=True)
ax1.plot(x1, y1)
ax1.set_title('Two plots')
ax2.plot(x2, y2)
but its giving error:但它给出的错误:
ValueError: could not convert string to float: PSEUDO
How I can plot them in one image using matplotlib?如何使用 matplotlib 在一张图像中绘制它们?
Try this:尝试这个:
x1 = ['sale','pseudo','test_mode']
y1 = [23, 51, 13]
x2 = ['ready','void']
y2 = [78, 1514]
y = y1+y2
x = x1+x2
pos = np.arange(len(y))
plt.bar(pos,y)
ticks = plt.xticks(pos, x)
Separate figures in one image:在一张图像中分离数字:
x1 = ['sale','pseudo','test_mode']
y1 = [23, 51, 13]
x2 = ['ready','void']
y2 = [78, 1514]
fig, (ax1, ax2) = plt.subplots(1, 2, sharey=True)
pos1 = np.arange(len(y1))
ax1.bar(pos1,y1)
plt.sca(ax1)
plt.xticks(pos1,x1)
pos2 = np.arange(len(y2))
ax2.bar(pos,y2)
plt.sca(ax2)
plt.xticks(pos2,x2)
The problem is that your x
values are not numbers, but text.问题是您的
x
值不是数字,而是文本。 Instead, plot the y
values and then change the name of the xticks (see this answer ):相反,绘制
y
值,然后更改 xticks 的名称(请参阅此答案):
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()
This produces:这产生:
For a bar graph, switch out ax.plot(y)
with ax.bar(range(len(x)), y)
.对于条形图,用
ax.bar(range(len(x)), y)
切换出ax.plot(y)
ax.bar(range(len(x)), y)
。 This will produce the following:这将产生以下内容:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.