3

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:

result of code

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

2 Answers 2

2

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: f.y - (-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()

resulting plot

Sign up to request clarification or add additional context in comments.

Comments

2

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

enter image description here

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.