1

I am a little annoyed. I am currently trying to plot bar graph values ontop of the bar graph but the values are misaligned. Is it possible to put the values inside of the corresponding bar graph? I did some digging around and found this which helped me to a certain extent: python - how to show values on top of bar plot

Here is what the plot looks like: enter image description here

my code:

    import pandas as pd
    import matplotlib.pyplot as plt
    from matplotlib.lines import Line2D
    import matplotlib

    df = pd.DataFrame({'Years': ['2015', '2016', '2017', '2018'],
                       'Value': [-495982.0, 405549.0, -351541.0, 283790.0]})
    values = df["Value"]
    #values = values / 1e3
    asOfDates = df['Years']

    Value = df['Value'] / 1000

    fig, ax, = plt.subplots()
    xlocs, xlabs = plt.xticks()
    ax.set_title('Plotting Financials')
    ax.set_xlabel('Years')
    ax.set_ylabel('value')
    plt.bar(asOfDates, values, color=['r' if v < 0 else 'g' for v in values])
    ax.get_yaxis().set_major_formatter(matplotlib.ticker.FuncFormatter(lambda x, p: format(int(x), ',')))
    for i, v in enumerate(values):
        ax.text(v + 3, i + .25, str(v), fontweight='bold')
        ax.text(xlocs[i] - 0.15, v + 0.01, str(v))

    plt.show()
AndrewRoj
  • 97
  • 1
  • 8
  • 1
    Related to [this](https://stackoverflow.com/questions/61782951/how-to-write-values-over-matplotlib-bar-charts-without-distorted-figures/61784661#61784661), although it is for horizontal bars. – Quang Hoang May 19 '20 at 15:19
  • 1
    You could use `f'{v:,.0f}'` instead of `str(v)` to get a friendlier formatted number – JohanC May 19 '20 at 16:33

1 Answers1

1

You switched the position of the x and the y values in the call to ax.text(). Moreover, you do not need it twice. You can also use 1.05 or some other value as a factor to control the y-value.

for i, v in enumerate(values):
    ax.text(i , v*1.05, str(v), fontweight='bold', va='center', ha='center')

enter image description here

Sheldore
  • 37,862
  • 7
  • 57
  • 71