使用Python校正matplotlib中的x值

使用Python校正matplotlib中的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
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()


^此图:
python - 使用Python校正matplotlib中的x值-LMLPHP

虽然这是我想要的方式:
python - 使用Python校正matplotlib中的x值-LMLPHP

x总是向右移动一个单位。我想要的是它在下降(红色条)和上升(绿色条)时仅向右移动一个单位。
有人知道怎么做吗? :)

最佳答案

您可以引入变量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()


python - 使用Python校正matplotlib中的x值-LMLPHP

关于python - 使用Python校正matplotlib中的x值,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/44380784/

10-12 23:54