使用Python编程编写一个绘图函数输入x、y输出带有数据标签、图例的柱状图
您可以使用Python中的matplotlib库来绘制带有数据标签和图例的柱状图。以下是一个示例代码:
import matplotlib.pyplot as plt
def plot_bar_chart(x, y):
fig, ax = plt.subplots()
bars = ax.bar(x, y)
# 添加数据标签
for bar in bars:
height = bar.get_height()
ax.annotate(f'{height}', xy=(bar.get_x() + bar.get_width() / 2, height),
xytext=(0, 3), textcoords="offset points",
ha='center', va='bottom')
ax.set_xlabel('X')
ax.set_ylabel('Y')
ax.set_title('Bar Chart')
# 添加图例
ax.legend(bars, ['Data'])
plt.show()
# 示例输入数据
x = ['A', 'B', 'C', 'D']
y = [10, 20, 15, 25]
# 调用绘图函数
plot_bar_chart(x, y)
在示例代码中,x和y分别是柱状图的横轴和纵轴数据。通过调用bar函数创建柱状图,并使用annotate函数添加数据标签。然后通过legend函数添加图例。最后调用show函数显示图形。
原文地址: https://www.cveoy.top/t/topic/i3Ph 著作权归作者所有。请勿转载和采集!