Reputation: 165
import matplotlib.pyplot as plt
import matplotlib.patches as patches
fig = plt.figure()
ax1 = fig.add_subplot(111)
numbers = [0, 1, 4, 5, 8, 5, 3, 2, 6, 7, 9, 11]
x = 0
for current, next in zip(numbers, numbers[1:]):
if (current < next):
up_bar = patches.Rectangle((x,current), 1, next-current, fc='green')
ax1.add_patch(up_bar)
else:
down_bar = patches.Rectangle((x,current), 1, next-current, fc='red')
ax1.add_patch(down_bar)
x += 1
ax1.set_xticks([0, 1, 2, 3, 4, 5, 6, 7, 8])
ax1.set_yticks([0, 1, 2, 3, 4, 5, 6, 7, 8])
plt.show()
x always shifts one unit to the right. What I want is for it to only shift one unit to the right when its going down(red bar) and going up(green bar). Does anyone know how to do it? :)
Upvotes: 1
Views: 49
Reputation: 2629
You can introduce a variable old_current
(not the best name, though) and check whether this your numbers have "made a turn". Only in this case you should increase x
. The following should fit your needs:
import matplotlib.pyplot as plt
import matplotlib.patches as patches
fig = plt.figure()
ax1 = fig.add_subplot(111)
numbers = [0, 1, 4, 5, 8, 5, 3, 2, 6, 7, 9, 11]
x = 0
old_current = 0
for current, next in zip(numbers, numbers[1:]):
if (current < next):
if (old_current > current):
x += 1
up_bar = patches.Rectangle((x,current), 1, next-current, fc='green')
ax1.add_patch(up_bar)
else:
if (old_current < current):
x += 1
down_bar = patches.Rectangle((x,current), 1, next-current, fc='red')
ax1.add_patch(down_bar)
old_current = current
ax1.set_xticks([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12])
ax1.set_yticks([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12])
ax1.set_xlim(0,12)
ax1.set_ylim(0,12)
plt.show()
Upvotes: 2