1

I want to plot two figures in one image using 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?

ImportanceOfBeingErnest
  • 321,279
  • 53
  • 665
  • 712
neha
  • 1,858
  • 5
  • 21
  • 35

2 Answers2

1

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)
malugina
  • 196
  • 1
  • 6
  • I can't draw like this. x1 and x2 are two different attributes. From your solution it will get plot as a one attribute. I want to make to separate figures for x1 and x2. Separate figure in one image. – neha Aug 11 '17 at 10:39
0

The problem is that your x values are not numbers, but text. Instead, plot the y values and then change the name of the xticks (see this 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()

This produces:

line graph

For a bar graph, switch out ax.plot(y) with ax.bar(range(len(x)), y). This will produce the following:

bar graph

pingul
  • 3,351
  • 3
  • 25
  • 43