matplotlib实现双y轴的一些问题

aizaidongzhi 2011-09-15 10:22:25

import matplotlib.pyplot as plt
import numpy as np

x = np.arange(0., np.e, 0.01)
y1 = np.exp(-x)
y2 = np.log(x)
fig = plt.figure()
ax1 = fig.add_subplot(111)
ax1.plot(x, y1);
ax1.set_ylabel('Y values for exp(-x)');
ax2 = ax1.twinx() # this is the important function
ax2.plot(x, y2, 'r');
ax2.set_xlim([0, np.e]);
ax2.set_ylabel('Y values for ln(x)');
ax2.set_xlabel('Same X for both exp(-x) and ln(x)');
plt.show()

在一个matpoltlib的指导书上看见的一个例子,现在我想添加上边两条曲线的标志label,该如何做呢?
我通过修改ax1.plot(x, y1)为
ax1.plot(x, y1, label="left")
ax1.legend();
把ax2.plot(x2, y2, 'r')改成
ax2.plot(x2, y2, label="right")
ax2.legend();
这样只出来的label只有右Y轴的曲线标志, 还有颜色如何控制,都是蓝色了。。。求高人指点
...全文
958 3 打赏 收藏 转发到动态 举报
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
黑夜愁客 2011-09-15
  • 打赏
  • 举报
回复
之前之所以只显示右边一个label,是因为在windows中legend()函数只选取当前活动的ax2,所以替换覆盖了之前的ax1.linux下测试好像没问题,不过在legend()函数中添加参数也可以做到。
黑夜愁客 2011-09-15
  • 打赏
  • 举报
回复
import matplotlib.pyplot as plt
import numpy as np

x = np.arange(0., np.e, 0.01)
y1 = np.exp(-x)
y2 = np.log(x)
fig = plt.figure()
ax1 = fig.add_subplot(111)
ax1.plot(x, y1,'r',label="right");
ax1.legend(loc=1)
ax1.set_ylabel('Y values for exp(-x)');
ax2 = ax1.twinx() # this is the important function
ax2.plot(x, y2, 'g',label = "left")
ax2.legend(loc=2)
ax2.set_xlim([0, np.e]);
ax2.set_ylabel('Y values for ln(x)');
ax2.set_xlabel('Same X for both exp(-x) and ln(x)');
plt.show()

我做了一些修改。那个label可以分别显示在左右 你自己测试,颜色我改好了。你也可以自己修改

37,721

社区成员

发帖
与我相关
我的任务
社区描述
JavaScript,VBScript,AngleScript,ActionScript,Shell,Perl,Ruby,Lua,Tcl,Scala,MaxScript 等脚本语言交流。
社区管理员
  • 脚本语言(Perl/Python)社区
  • IT.BOB
加入社区
  • 近7日
  • 近30日
  • 至今

试试用AI创作助手写篇文章吧