【问题标题】:Display just one legend for two plots with matplotlib使用 matplotlib 仅显示两个图的一个图例
【发布时间】:2020-07-28 20:09:56
【问题描述】:

我正在尝试使用“绘图”两次绘制图表。但我只需要图例出现一次,因为这两个图的图例相同。这是带有示例的代码:

# data
example_data = {'x': [-6,-5,-4,-3,-2,-1,0,1,2,3,4,5,6],
                'y': [10, 11, 13, 12, 14, 14, 15, 17, 18, 21, 23, 23, 24]}
df = pd.DataFrame(example_data)

# plot
fig, ax = plt.subplots(figsize=(7,5))
plt.plot('x', 'y', data=df.query('x < 0'), marker='o', color='b', label='something') # the legend I want to show in the chart
plt.plot('x', 'y', data=df.query('x > 0'), marker='o', color='b')
plt.legend();

此代码生成以下图表:

(这里我只有一条线,因为它只是一个例子。在我的原始图表中我有不止一条,所以我需要图例)

如您所见,当我调用“plt.legend()”时,它会激活两个图的图例。所以我的问题是:我怎样才能只显示其中一个?

【问题讨论】:

  • 不使用label=''(空字符串)?
  • matplotlib 中有一个奇怪的技巧。试试label='_no_legend'
  • 非常感谢 Bruno 和 Paul H。他们都工作了。我不知道技巧'_no_legend'。显然它就像布鲁诺建议的空字符串一样工作。再次感谢您!
  • 通常如果你不设置label你也不会得到一个图例,但在这种情况下你使用一个字符串'y'来访问data对象,所以Matplotlib使用不管你喜不喜欢,它都是默认标签。
  • 我放了一个答案来帮助有同样问题的人不必阅读评论,因为答案是不可见的。但也许你自己回答会更好?在那种情况下说我,我删除我的答案

标签: python matplotlib


【解决方案1】:

第一种方法是为标签使用空字符串:

plt.plot('x', 'y', data=df.query('x > 0'), marker='o', color='b', label='')

Paul H 给出的第二种方法是使用技巧“_no_legend”作为标签

plt.plot('x', 'y', data=df.query('x > 0'), marker='o', color='b', label='_no_legend')

两种方式都隐藏标签,例如:

import matplotlib.pyplot as plt
import pandas as pd

# data
example_data = {'x': [-6,-5,-4,-3,-2,-1,0,1,2,3,4,5,6],
                'y': [10, 11, 13, 12, 14, 14, 15, 17, 18, 21, 23, 23, 24]}
df = pd.DataFrame(example_data)

# plot
fig, ax = plt.subplots(figsize=(7,5))
plt.plot('x', 'y', data=df.query('x < 0'), marker='o', color='b', label='something') # the legend I want to show in the chart
plt.plot('x', 'y', data=df.query('x > 0'), marker='o', color='b', label='') # the legend to not show
plt.legend();
fig.show();

产生:

【讨论】:

    猜你喜欢
    • 2020-02-05
    • 2019-02-27
    • 2020-10-20
    • 1970-01-01
    • 2014-03-26
    • 2021-12-17
    • 1970-01-01
    • 2019-08-21
    • 2021-01-19
    相关资源
    最近更新 更多