matplotlib: TypeError: аргумент float () должен быть строкой или числом, а не 'AxesSubplot' - PullRequest
0 голосов
/ 17 марта 2020

Я работаю над учебниками по matplotlib. У меня есть рабочий сюжет, который я хотел бы обобщить с помощью функции. Сюжет работает, однако, когда я определяю функцию red_grid_plot() ниже, я получаю сообщение об ошибке:

TypeError: float() argument must be a string or a number, not 'AxesSubplot'

, и я не могу определить из трассировки источник ошибки. Рабочий график:

from alpha_vantage.timeseries import TimeSeries
import pandas as pd
import datetime
import matplotlib.pyplot as plt

ts = TimeSeries(key="XXXXXX", output_format='pandas')
df, meta_data = ts.get_daily_adjusted(symbol='TSLA', outputsize='full')

df.columns = df.columns.str[3:]
tesla = df[(df.index > '2019-05-01')]

fig, ax = plt.subplots(figsize=(12,6))

ax.plot(tesla['close'], 'r-', linewidth=2)

kwargs=dict(labelsize=12, direction='inout',
            length=6, color='r', width=2)

ax.tick_params(axis="x", rotation=45, **kwargs)
ax.tick_params(axis="y", **kwargs)

ax.minorticks_on()
ax.grid(axis="x", linestyle=':', linewidth='0.5', color='red')
ax.grid(axis="y", linestyle=':', linewidth='0.5', color='black')

fig.suptitle('TSLA Daily Close', fontsize=16)

plt.show()

производит:

enter image description here

Я определяю функцию red_grid_plot() как:

def red_grid_plot(x, y, ax, param_dict):

tic_kwargs=dict(labelsize=12, 
                direction='inout',
                length=6, 
                color='r', 
                width=2)

grd_kwargs=dict(linestyle=':', 
                linewidth='0.5')

ax.tick_params(axis="x", rotation=45, **tic_kwargs)
ax.tick_params(axis="y", **tic_kwargs)

ax.minorticks_on()

ax.grid(axis="x", color='red', **grd_kwargs)
ax.grid(axis="y", color='black', **grd_kwargs)

if isinstance(x, pd.DataFrame):
    x = x.values
else:
    x = x.to_numpy()

if isinstance(y, pd.DataFrame):
    y = y.values
else:
    y = y.to_numpy()

out = ax.plot(x, y, ax, **param_dict)
return out 

Когда я вызываю эту функцию, я получаю:

TypeError: float() argument must be a string or a number, not 'AxesSubplot'

На какой аргумент float жалуется трассировка? Я предположил, что он жаловался на столбец или индекс Pandas, требующий преобразования в массив numpy перед вызовом метода plot(), поэтому тесты if / else, но это не проблема.

Вот весь след:

TypeError                                 Traceback (most recent call last)
<ipython-input-5-02ee0c0b3a19> in <module>
      1 fig, ax = plt.subplots(figsize=(12,6))
----> 2 red_grid_plot(tesla.index, tesla['close'], ax, {'linewidth': 2})

<ipython-input-4-e35299a48436> in red_grid_plot(x, y, ax, param_dict)
     28         y = y.to_numpy()
     29 
---> 30     out = ax.plot(x, y, ax, **param_dict)
     31     return out

~\Anaconda3\lib\site-packages\matplotlib\axes\_axes.py in plot(self, scalex, scaley, data, *args, **kwargs)
   1665         lines = [*self._get_lines(*args, data=data, **kwargs)]
   1666         for line in lines:
-> 1667             self.add_line(line)
   1668         self.autoscale_view(scalex=scalex, scaley=scaley)
   1669         return lines

~\Anaconda3\lib\site-packages\matplotlib\axes\_base.py in add_line(self, line)
   1900             line.set_clip_path(self.patch)
   1901 
-> 1902         self._update_line_limits(line)
   1903         if not line.get_label():
   1904             line.set_label('_line%d' % len(self.lines))

~\Anaconda3\lib\site-packages\matplotlib\axes\_base.py in _update_line_limits(self, line)
   1922         Figures out the data limit of the given line, updating self.dataLim.
   1923         """
-> 1924         path = line.get_path()
   1925         if path.vertices.size == 0:
   1926             return

~\Anaconda3\lib\site-packages\matplotlib\lines.py in get_path(self)
   1025         """
   1026         if self._invalidy or self._invalidx:
-> 1027             self.recache()
   1028         return self._path
   1029 

~\Anaconda3\lib\site-packages\matplotlib\lines.py in recache(self, always)
    673         if always or self._invalidy:
    674             yconv = self.convert_yunits(self._yorig)
--> 675             y = _to_unmasked_float_array(yconv).ravel()
    676         else:
    677             y = self._y

~\Anaconda3\lib\site-packages\matplotlib\cbook\__init__.py in _to_unmasked_float_array(x)
   1388         return np.ma.asarray(x, float).filled(np.nan)
   1389     else:
-> 1390         return np.asarray(x, float)
   1391 
   1392 

~\Anaconda3\lib\site-packages\numpy\core\_asarray.py in asarray(a, dtype, order)
     83 
     84     """
---> 85     return array(a, dtype, copy=False, order=order)
     86 
     87 

TypeError: float() argument must be a string or a number, not 'AxesSubplot'
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...