如何用熊猫把传说放在情节之外

时间:2014-05-09 03:31:45

标签: python matplotlib pandas

如何将图例放在情节之外?

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()

3 个答案:

答案 0 :(得分:48)

我认为您需要在添加呼叫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()

答案 1 :(得分:3)

我可以根据 OP 的问题使用以下代码段将图例放在图表外:

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()

它在我的笔记本中的显示方式: enter image description here

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

答案 2 :(得分:0)

这对我有用

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