【问题标题】:How to put legend outside the plot with pandas如何用熊猫把传说放在情节之外
【发布时间】:2014-06-26 16:39:48
【问题描述】:

怎么可能把图例放在情节之外?

import pandas as pd
import matplotlib.pyplot as plt
a = {'Test1': {1: 21867186, 4: 20145576, 10: 18018537},
    'Test2': {1: 23256313, 4: 21668216, 10: 19795367}}

d = pd.DataFrame(a).T
#print d

f = plt.figure()

plt.title('Title here!', color='black')
plt.legend(loc='center left', bbox_to_anchor=(1, 0.5))
d.plot(kind='bar', ax=f.gca())
plt.show()

【问题讨论】:

  • 实际上它不是完全重复的......这个问题是专门针对熊猫的。下面的响应显示了如何将轴分配给来自pandas.DataFrame.plot 的绘图函数调用,这使得应用matplotlib.pyplot 改进成为可能。
  • 是的,这不是重复的,它被标记为这样很烦人。
  • 这不是重复的,因为它适用于 Pandas .plot。感谢@matt_harrison,下面概述了解决方案,但总结一下:如果您有d.plot(kind='bar', ax=f.gca()),请将其更改为d.plot(kind='bar', ax=f.gca()).legend(bbox_to_anchor=(1,1))
  • 看看这个人:stackoverflow.com/questions/4700614/… 它有很好的讨论/答案,如果你知道最小的 pandas/matplotlib,这个问题几乎是那个问题的副本。

标签: python matplotlib pandas


【解决方案1】:

我认为您需要先调用plot,然后再添加调用legend

import pandas as pd
import matplotlib.pyplot as plt
a = {'Test1': {1: 21867186, 4: 20145576, 10: 18018537},
    'Test2': {1: 23256313, 4: 21668216, 10: 19795367}}

d = pd.DataFrame(a).T
#print d

f = plt.figure()

plt.title('Title here!', color='black')
d.plot(kind='bar', ax=f.gca())
plt.legend(loc='center left', bbox_to_anchor=(1.0, 0.5))
plt.show()

-----熊猫解决方案 如果您使用的是 pandas Dataframe.plot

dataframe_var.plot.bar().legend(loc='center left',bbox_to_anchor=(1.0, 0.5));

【讨论】:

  • 但是,图例的一半现在不在图片中?怎么可能修复它?
  • 这确实是一个单独的问题,但你可以试试f.subplots_adjust(right=0.8)
  • 如果你只是想移动图例,你可以利用.plot返回一个matplotlib轴并将.legend(bbox_to_anchor=(1,1))添加到你的代码行末尾
  • @mattharrison 的评论应该是答案。
  • 我不认为这是一个单独的问题,重点是移动图例,我不明白为什么图例移动后会突然半切。
【解决方案2】:

根据 OP 的问题,我可以使用以下 sn-p 将图例放在图表之外:

import pandas as pd
import matplotlib.pyplot as plt
a = {'Test1': {1: 21867186, 4: 20145576, 10: 18018537},
    'Test2': {1: 23256313, 4: 21668216, 10: 19795367}}

df = pd.DataFrame(a).T

ax = df.plot.bar()
ax.set_title("Title here!",color='black')
ax.legend(bbox_to_anchor=(1.0, 1.0))
ax.plot()

它在我的笔记本中的显示方式:

然后,您可以修改锚点值以根据需要调整其位置。锚点将是该图表的左下角。

【讨论】:

  • 感谢@CodeBender!那个简单的答案就是我需要的!!
【解决方案3】:

这对我有用

ax = df.plot(kind='bar')
ax.yaxis.set_major_formatter(mtick.PercentFormatter())
ax.legend(loc='center left', bbox_to_anchor=(1.0, 0.5)) #here is the magic

【讨论】:

    猜你喜欢
    • 2017-04-12
    • 2016-03-24
    • 2021-11-25
    • 2020-02-28
    • 1970-01-01
    • 2021-12-09
    • 2018-05-07
    • 2016-11-15
    相关资源
    最近更新 更多