简体   繁体   English

Python:从负 Y 值开始的 Matplotlib 条

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

I am trying to plot negative values with bars in Python, which start from a low negative value and end at the given negative value.我正在尝试使用 Python 中的条形来 plot 负值,它从低负值开始并以给定的负值结束。 This is how it should look (Excel-Plot), negative values' bars starting at -60:这就是它的外观(Excel-Plot),负值条从 -60 开始:

Here the definition of the horizontal axis intersection at "-60" does the trick.在这里,“-60”处的水平轴交点的定义起到了作用。

My code:我的代码:

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

shows:显示:

代码结果

The bars start at -60, but the inverse y-axis values ruin it.条形图从 -60 开始,但反向 y 轴值破坏了它。

Is there any way to plot bars growing from the bottom up to their negative value, with the correct y-axis values (for example, bottom y-value: -60, top y-value: 0)?有没有办法让 plot 条从底部向上增长到负值,并且 y 轴值正确(例如,底部 y 值:-60,顶部 y 值:0)?

Your y values are negative, so the bars go in the negative direction.您的 y 值为负数,因此条形图 go 在负方向。 You need to invert the sign of your data.您需要反转数据的符号。 Furthermore, you still want the y-axis to go from lower to greater values, so you don't want it inverted.此外,您仍然希望 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

在此处输入图像描述

It seems you want bars that start at -60 and stop at the given y values.似乎您想要从-60开始并在给定y值处停止的条形图。 However, the second parameter of plt.bar() is the bar height, not its end point.然而, plt.bar()的第二个参数是柱的高度,而不是它的终点。

You can calculate the height by subtracting the bottom from the desired y values: fy - (-60) .您可以通过从所需的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