在Python中,添加数据标签通常使用`matplotlib`库,以下是添加数据标签的几种常见方法:
方法一:使用`annotate`函数添加标签
import matplotlib.pyplot as plt
x = [1, 2, 3, 4, 5]
y = [2, 4, 6, 8, 10]
plt.plot(x, y)
for i, j in zip(x, y):
plt.annotate(str(j), xy=(i, j), xytext=(10, -10), textcoords='offset points')
plt.show()
方法二:使用`text`方法添加标签
import matplotlib.pyplot as plt
x = [1, 2, 3, 4, 5]
y = [2, 3, 5, 7, 11]
plt.scatter(x, y)
for i in range(len(x)):
plt.text(x[i], y[i], f'({x[i]}, {y[i]})')
plt.show()
方法三:使用`bar_label`函数添加柱状图标签
import matplotlib.pyplot as plt
X_set = [1, 2, 3, 4, 5]
Y_set = [128, 211, 136, 234, 150]
p1 = plt.bar(X_set, Y_set, width=0.35, label='value')
plt.bar_label(p1, label_type='edge') 标签放在柱子顶端
plt.title('The distribution of XXX')
plt.show()
方法四:使用`plot`函数添加折线图标签
import matplotlib.pyplot as plt
x_arr = [1, 2, 3, 4, 5, 6]
y_arr = [1, 4, 9, 16, 25, 36]
plt.plot(x_arr, y_arr, 'g*-')
for x, y in zip(x_arr, y_arr):
plt.text(x, y + 0.3, str(y), ha='center', va='bottom', fontsize=10.5)
plt.savefig('fig' + str(int(time.time())) + '.jpg')
plt.show()