条形图上未对齐的值

时间:2020-05-19 15:10:20

标签: python matplotlib

我有点生气。我目前正在尝试在条形图的顶部绘制条形图的值,但这些值未对齐。是否可以将值放在相应的条形图中?我进行了一些挖掘,发现这对我有所帮助:python - how to show values on top of bar plot

这是情节的样子: enter image description here

我的代码:

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

1 个答案:

答案 0 :(得分:1)

您已将呼叫中的x和y值的位置切换为ax.text()。而且,您不需要两次。您还可以使用1.05或其他某个值作为控制y值的因素。

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

enter image description here