gpt4 book ai didi

python - 使用 Python 更正 matplotlib 中的 x 值

转载 作者:行者123 更新时间:2023-12-01 02:54:18 25 4
gpt4 key购买 nike

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()

^此图: enter image description here

虽然这就是我想要的: enter image description here

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()

Bar graph

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

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com