在matplotlib上为条形添加值标签

时间:2018-10-10 10:42:43

标签: python python-3.x matplotlib

我有一个这样的数据框:

B6PO0510_S1C1   B6PO0510_S1C2   B6PO0510_S2C1   B6PO0510_S2C2   B6PO0510_S3C1   B6PO0510_S3C2   index1
44544   44544   44544   44544   44544   44544   250
30360   11438   26340   5260    4320    2071    500
26989   4737    52545   6857    4423    36060   750
4681    759    18236    29725   6208    80152   1000
944     520     3846    388     1971    43238   1250
2341    2098    1966    191     2955    7917    1500
4122    314      296    9        389    6989    1750
852     27      3469    336     1437    2356    2000
131    114      1966    30      251     1651    2250
82     658      184     1       14      3035    2500
4       21        8     4       40      860     2750
22      31       10     52      109     1912    3000
0       20        4     3        173    159     3250
55      8         1    262      396     596    3500
80      3        0      84      29      445     3750
0      4        234     0      68       5       4000

我正在绘制带有单选按钮的条形图。这是我的代码:

import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.widgets import RadioButtons

df5=pd.read_excel(r'C:\YOIGO\text\graphs\hi.xlsx')

fig, ax = plt.subplots()
bars = ax.bar(np.array(df5.index1), height=np.array(df5['index1']), color='red', width=200)
ax.set_xticks((df5.index1))
ax.set_xticklabels(tuple(df5.index1))
plt.subplots_adjust(left=0.3)


axcolor = 'lightgoldenrodyellow'
rax = plt.axes([0.05, 0.7, 0.15, 0.15], facecolor=axcolor)
radio = RadioButtons(rax, df5.columns[:-1])


def hzfunc(label):
    ydata = df5[label]
    for b,y in zip(bars,ydata):
        b.set_height(y)
    plt.draw()

radio.on_clicked(hzfunc)

def onpick(event):
    thisline = event.artist
    xdata = thisline.get_xdata()
    ydata = thisline.get_ydata()
    ind = event.ind
    print ('onpick points:', zip(xdata[ind], ydata[ind]))

fig.canvas.mpl_connect('pick_event', onpick)


plt.show()

这段代码给了我这样的情节:

enter image description here

x轴上的值重叠,甚至单选按钮值在图形上也重叠。 我想消除这种重叠,并为每个栏添加栏值。 我可以知道怎么做吗?

0 个答案:

没有答案