如何将熊猫的传说置于情节之外

怎么可能把传说排除在情节之外呢?

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()
139415 次浏览

我认为您需要调用 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()

- 熊猫解决方案 如果您正在使用熊猫 Dataframe.plot

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

这对我有用

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

根据 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

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

我觉得这个更容易使用,任何反馈都很感激

df.plot(kind='area')
plt.legend(loc=(1.01,.35)) #here I tried to keep it outside middle right