如何使用 Pandas 将图例放在图表之外?
pandaspythonserver side programmingprogramming
要使用 Pandas 将图例放在图表之外,我们可以采取以下步骤 −
创建一个字典 d,其键为 Column1 和 Column2。
使用 DataFrame (d) 创建一个数据框。
使用样式列表绘制数据框。
使用 legend() 在图形上放置图例。bbox_to_anchor 关键字为手动图例放置提供了很大程度的控制。例如,如果您希望轴图例位于图形的右上角,而不是轴的角,只需指定角的位置以及该位置的坐标系即可。
要显示图形,请使用 show() 方法。
示例
import pandas as pd from matplotlib import pyplot as plt plt.rcParams["figure.figsize"] = [7.50, 3.50] plt.rcParams["figure.autolayout"] = True d = {'Column 1': [i for i in range(10)], 'Column 2': [i * i for i in range(10)]} df = pd.DataFrame(d) df.plot(style=['o', 'rx']) plt.legend(bbox_to_anchor=(1.0, 1.0)) plt.show()