如何解决如何通过指定行和列从轴对象返回特定轴?
我在 Jupyter Notebook 上学习 Python 已经有一段时间了,因为我的导师会布置作业。本周我需要实现一个函数,它执行以下操作:
实现函数 selected_axis 以便使用函数 plot_subplots 绘制以下图。 查看 plot_subplots 函数以了解您的函数接收什么作为参数以及预期返回值是什么。
我已经加载了以下库:
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
这里我得到了 plot_subplots 函数:
def plot_subplots(data,nb_rows,nb_cols,row,col):
fig,axes = plt.subplots(nb_rows,sharex=True,sharey=True)
axis = selected_axis(axes,col,nb_cols)
axis.plot(data)
plt.show()
# Plot a linear function in a 3x3 matrix at position 1,2
plot_subplots(np.arange(1,9),3,1,2)
注释显示函数如何工作,以及它接收哪些变量。所以我继续实现我的函数selected_axis:
def selected_axis(axes,nb_cols):
a = []
if row <= nb_rows and col <= nb_cols:
for column_id,rows in enumerate(axes):
if column_id == col - 1:
a.append(col-1)
for row_id,row_value in enumerate(rows):
if row_id == row - 1:
a.append(row-1)
axis = axes[a[1],a[0]]
return axis
如果我运行 plot_subplots(np.arange(1,2)
,则会给出以下输出,这似乎与我被要求实现的目标一致,即在所需的子图中绘图:
Output of plot_subplots(np.arange(1,2)
现在,我面临着我的导师实施的以下测试单元:
# Test cell.
from unittest import TestCase
__ = TestCase()
_data,_rows,_cols,_row,_col = np.arange(1,2
_fig,_axes = plt.subplots(_rows,sharey=True)
_ax = selected_axis(_axes,_col,_cols)
__.assertTrue(_ax.get_subplotspec().colspan.start == _col and _ax.get_subplotspec().rowspan.start == _row,msg="Your function does not select the correct axis.")
_ax.plot(_data)
plt.show()
_data,2,5,4
_fig,msg="Your function does not select the correct axis.")
_ax.plot(_data)
plt.show()
_fig,_axes = plt.subplots(2,sharey=True)
selected_axis(_axes,2).plot(np.arange(-5,0.1) ** 2)
selected_axis(_axes,2).plot(-np.arange(-5,0.1) ** 3)
selected_axis(_axes,0.1) ** 3)
__.assertTrue(_ax.get_subplotspec().colspan.start == _col and _ax.get_subplotspec().rowspan.start == _row,msg="Your function does not select the correct axis.")
_ax.plot(_data)
plt.show()
__.assertRaises(ValueError,selected_axis,_axes,1000,312,_cols)
print("\n\033[37;42;2m Success! Your code works as intended. \033[0m\n")
执行它时,我收到以下错误消息:
---------------------------------------------------------------------------
AssertionError Traceback (most recent call last)
<ipython-input-129-fb042c0cacf0> in <module>
8 _ax = selected_axis(_axes,_cols)
9
---> 10 __.assertTrue(_ax.get_subplotspec().colspan.start == _col and _ax.get_subplotspec().rowspan.start == _row,11 msg="Your function does not select the correct axis.")
12 _ax.plot(_data)
~\anaconda3\lib\unittest\case.py in assertTrue(self,expr,msg)
763 if not expr:
764 msg = self._formatMessage(msg,"%s is not true" % safe_repr(expr))
--> 765 raise self.failureException(msg)
766
767 def _formatMessage(self,msg,standardMsg):
AssertionError: False is not true : Your function does not select the correct axis.
截至目前,我完全不知道为什么测试单元没有给我预期的结果..
如果有人能帮助我,我将不胜感激!
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。