Python 多个轴的单个图例
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14344063/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Single legend for multiple axes
提问by arun
I have the following example code:
我有以下示例代码:
fig1.suptitle('Test')
ax1 = fig1.add_subplot(221)
ax1.plot(x,y1,color='b',label='aVal')
ax2 = ax1.twinx()
ax2.plot(x,y2,color='g',label='bVal')
ax2.grid( ls='--', color='black')
legend([ax1,ax2], loc=2)
The subplot has two axes with different scales on the same subplot and I want only one legend for both axes. I tried the above code and it does not work and only produces details from ax2. Any ideas?
子图在同一个子图上有两个不同比例的轴,我只想要两个轴都有一个图例。我尝试了上面的代码,但它不起作用,只能从 ax2 生成详细信息。有任何想法吗?
采纳答案by arun
I figured it a solution that works! Is there a better way than this?
我认为这是一个有效的解决方案!还有比这更好的方法吗?
fig1.suptitle('Test')
ax1 = fig1.add_subplot(221)
ax1.plot(x,y1,color='b',label='aVal')
ax2 = ax1.twinx()
ax2.plot(x,y2,color='g',label='bVal')
ax2.grid( ls='--', color='black')
h1, l1 = ax1.get_legend_handles_labels()
h2, l2 = ax2.get_legend_handles_labels()
ax1.legend(h1+h2, l1+l2, loc=2)
回答by Cy Bu
This is indeed an old post, but I think I found an easier way allowing more control.
这确实是一篇旧帖子,但我想我找到了一种更简单的方法,可以进行更多控制。
Here it is (matplotlib.version'1.5.3') on python3.5:
这是python3.5上的(matplotlib。版本'1.5.3'):
import matplotlib.pyplot as plt
fig, ax1 = plt.subplots()
plt.suptitle('Test')
ax2 = ax1.twinx()
a, = ax1.plot([1, 2, 3], [4, 5, 6], color= 'blue', label= 'plt1')
b, = ax2.plot([7, 8, 9],[10, 11, 12], color= 'green', label= 'plt2')
p = [a, b]
ax1.legend(p, [p_.get_label() for p_ in p],
loc= 'upper center', fontsize= 'small')


