简体   繁体   中英

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. This is how it should look (Excel-Plot), negative values' bars starting at -60:

Here the definition of the horizontal axis intersection at "-60" does the trick.

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.

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

Your y values are negative, so the bars go in the negative direction. 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.

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. However, the second parameter of plt.bar() is the bar height, not its end point.

You can calculate the height by subtracting the bottom from the desired y values: 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()

结果图

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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