繁体   English   中英

Python:从负 Y 值开始的 Matplotlib 条

[英]Python: Matplotlib Bars Starting from Negative Y-Values

我正在尝试使用 Python 中的条形来 plot 负值,它从低负值开始并以给定的负值结束。 这就是它的外观(Excel-Plot),负值条从 -60 开始:

在这里,“-60”处的水平轴交点的定义起到了作用。

我的代码:

import matplotlib.pyplot as plt
import pandas as pd
f = pd.DataFrame({"x":range(9), "y": [-21,-24,-27,-30,-33, -36,-39,-42,-45 ]})
plt.bar(f.x, f.y, bottom= -60)
plt.gca().invert_yaxis()
plt.show()

显示:

代码结果

条形图从 -60 开始,但反向 y 轴值破坏了它。

有没有办法让 plot 条从底部向上增长到负值,并且 y 轴值正确(例如,底部 y 值:-60,顶部 y 值:0)?

您的 y 值为负数,因此条形图 go 在负方向。 您需要反转数据的符号。 此外,您仍然希望 y 轴从较低值到较大值 go,因此您不希望它倒置。

plt.bar(f.x, -f.y, bottom= -60)

#plt.gca().invert_yaxis() -> do not invert yaxis - you still want it to go in the same direction

在此处输入图像描述

似乎您想要从-60开始并在给定y值处停止的条形图。 然而, plt.bar()的第二个参数是柱的高度,而不是它的终点。

您可以通过从所需的y值中减去底部来计算高度: fy - (-60)

import matplotlib.pyplot as plt
import pandas as pd

f = pd.DataFrame({"x": range(1, 10), "y": [-21, -24, -27, -30, -33, -36, -39, -42, -45]})
plt.bar(f.x, f.y + 60, bottom=-60, color='darkorange')
plt.ylim(-60, 0)
plt.margins(x=0.02) # reduce the x margins a bit
plt.grid(axis='y', color='grey', lw=0.5)
ax = plt.gca()
ax.set_axisbelow(True)
for s in ['left', 'right', 'top']:
    ax.spines[s].set_visible(False)
plt.xticks(range(1, 10))
plt.show()

结果图

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM