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总是将一个单位向右移动。我想要的是它只有一个单位向下移动(红色条)和向上移动(绿色条)。 有谁知道怎么做? :)
答案 0 :(得分:2)
你可以引入一个变量old_current
(不是最好的名字)并检查你的数字是否“转了”。只有在这种情况下,您才应该增加x
。以下内容应符合您的需求:
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()