【问题标题】:Create a legend with pandas and matplotlib.pyplot使用 pandas 和 matplotlib.pyplot 创建图例
【发布时间】:2014-03-30 23:39:09
【问题描述】:

这是我第一次尝试使用 python 进行绘图,但在创建图例时遇到了问题。

这些是我的导入:

import matplotlib.pyplot as plt
import pandas

我这样加载我的数据:

data = pandas.read_csv( 'data/output/limits.dat', sep=r"\s+", encoding = 'utf-8' )

并像这样绘制它:

axdata = data.plot( label = '$|U|^{2}$' , x = 'mass', y = 'U2',
                    style = '-s', markeredgecolor = 'none' )

显然 axdata 现在是 AxesSubplot

现在我想创建一个像 here 这样描述的图例:

plt.legend( (line1), ('label1') )

但我不知道如何从AxesSubplot 中提取line 对象

plt.legend() 自己的作品,但我只希望我的一些台词出现在图例中。这是正确的方法吗?我可以在这里使用其他命令吗?

编辑

例如,如果我尝试:

plt.legend( [axdata], ['U2'])

我得到错误:

~/.virtualenvs/science/lib/python3.3/site-packages/matplotlib/legend.py:613:
UserWarning: Legend does not support Axes(0.125,0.1;0.775x0.8)
Use proxy artist instead.

http://matplotlib.sourceforge.net/users/legend_guide.html#using-proxy-artist

(str(orig_handle),))

我还没有弄清楚代理艺术家是什么,但我认为它是您使用非默认图形对象时的工具,我认为这里可能不是这种情况,因为我正在尝试制作一个正常的 matlibplot 图。 “非默认”和“正常”这两个词是我的 - 我还不确定它们的含义。

另一个编辑:(因为我误读了评论)

plt.legend() 本身不会向控制台输出任何内容,但生成的绘图现在具有从绘图数据自动生成的图例。

【问题讨论】:

  • 您可以提供更多信息吗?也许是 plt.legend() 输出的示例以及您希望图例输出的内容?这将极大地帮助我们了解如何为您提供帮助:)
  • 如果你这样做ax.legend()plt.draw()会发生什么?
  • 我得到一个图例,但它包含所有行的条目,而不仅仅是返回我的原始 axdata 对象的行。

标签: python matplotlib pandas


【解决方案1】:

我认为你想要做的是能够为你的情节上的一部分线条显示一个图例。应该这样做:

df = pd.DataFrame(np.random.randn(400, 4), columns=['one', 'two', 'three', 'four'])
ax1 = df.cumsum().plot()
lines, labels = ax1.get_legend_handles_labels()
ax1.legend(lines[:2], labels[:2], loc='best')  # legend for first two lines only

给予

【讨论】:

  • 这正是我想要做的。不幸的是,当我调用data.plot()(根据熊猫文档应该是plt.plot() 的包装器)时,返回的对象不支持get_legend_handles_labels()。我不知道如何从中提取行或将其转换为ax1 是您的示例的任何类型
  • ax1 是从对pandas.DataFrame.plot() 的调用返回的matplotlib.axes.AxesSubplot。这正是data.plot() 应该返回的内容。如果不运行代码进行调试,我不确定问题可能是什么,抱歉。
  • 这是一个错字:(。原来我拼错了标签。感谢您的演示。
猜你喜欢
  • 2016-11-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-10-30
  • 2013-12-29
  • 2020-08-15
相关资源
最近更新 更多