Python 柱状图添加图例:使用 Matplotlib legend 函数
{"title":"Python 柱状图添加图例:使用 Matplotlib legend 函数","description":"本教程介绍如何使用 Matplotlib 库中的 legend 函数在 Python 柱状图中添加图例,并提供一个简单的代码示例。","keywords":"python, 柱状图, 图例, matplotlib, legend, 数据可视化","content":"要在 Python 中添加柱状图的图例,可以使用 matplotlib 库的 legend 函数来实现。以下是一个简单的示例代码:\n\npython\nimport matplotlib.pyplot as plt\n\n# 创建数据\nx = [1, 2, 3, 4, 5]\ny1 = [10, 8, 6, 4, 2]\ny2 = [5, 4, 3, 2, 1]\n\n# 绘制柱状图\nplt.bar(x, y1, label='柱状图1')\nplt.bar(x, y2, label='柱状图2')\n\n# 添加图例\nplt.legend()\n\n# 显示图形\nplt.show()\n
\n\n在上面的示例中,我们首先创建了两个数据集 x、y1 和 y2,然后使用 plt.bar 函数绘制了两个柱状图。接下来,我们使用 plt.legend 函数添加图例,其中 label 参数用于指定每个柱状图的标签。最后,使用 plt.show 函数显示图形。\n\n运行代码后,将会显示一个带有图例的柱状图。图例将显示每个柱状图的标签,以便更好地区分它们。"}
原文地址: http://www.cveoy.top/t/topic/pNpR 著作权归作者所有。请勿转载和采集!