如何将图例放在情节之外?
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()
答案 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()
然后您可以修改锚点值以根据需要调整其位置。锚点将是此图表的左下角。
答案 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