0

I have a pandas dataframe, with multiple columns and thousands of rows.

I'm creating a set of graphs that will show diurnal profiles computed by month, from pandas dataframe.

I am trying to make a diurnal plot of gaseous conc vs time, and I am facing the error below

import pandas as pd
import matplotlib
from matplotlib import dates as d
import datetime as dt
import matplotlib.pyplot as plt
import numpy as np
data = pd.DataFrame( 
    columns = ['From Date',   'NO',          'NO2',       'NOx',    'CO',           'Ozone'],           
    data = [
        ['2018-12-30 00:00:00', 5.856666,    39.208341,   28.97,   331.280881,  19.778900],
        ['2018-12-30 01:00:00', 4.050059,    16.262145,   13.53,   454.031703,  25.075286],
        ['2018-12-30 02:00:00', 4.057806,    15.293990,   12.96,   466.502681,  24.825294],
        ['2018-12-30 03:00:00', 3.835476,    13.526193,   11.71,   446.526784,  25.033312],
        ['2018-12-30 04:00:00', 4.230690,    11.251531,   10.70,   355.638469,  25.748796]
    ]
)
data["From Date"]= pd.to_datetime(data["From Date"])
data.set_index('From Date',inplace=True)
data.replace('NoData', np.nan, inplace= True)

data['Time'] = data.index.map(lambda x: x.strftime("%H:%M"))
data.index = pd.to_datetime(data.index.astype(str))
data = data.groupby('Time').describe().unstack()
fig, ax = plt.subplots(1, figsize=(12,6))
ax.set_title('Diurnal Profile', fontsize=14)
ax.set_ylabel('Gas Concentrations', fontsize=14, weight='bold')
ax.set_xlabel('Time of Day', fontsize=14)
ax.plot(data.index, data['NOx']['mean'], 'g', linewidth=2.0)

The traceback of the error is as follows-

TypeError                                 Traceback (most recent call last)
<ipython-input-65-cfd03e5ac398> in <module>
      3 ax.set_ylabel('Gas Concentrations', fontsize=14, weight='bold')
      4 ax.set_xlabel('Time of Day', fontsize=14)
----> 5 ax.plot(data.index, data['NOx']['mean'], 'g', linewidth=2.0)

E:\python\lib\site-packages\matplotlib\axes\_axes.py in plot(self, scalex, scaley, data, *args, **kwargs)
   1664         """
   1665         kwargs = cbook.normalize_kwargs(kwargs, mlines.Line2D._alias_map)
-> 1666         lines = [*self._get_lines(*args, data=data, **kwargs)]
   1667         for line in lines:
   1668             self.add_line(line)

E:\python\lib\site-packages\matplotlib\axes\_base.py in __call__(self, *args, **kwargs)
    223                 this += args[0],
    224                 args = args[1:]
--> 225             yield from self._plot_args(this, kwargs)
    226 
    227     def get_next_color(self):

E:\python\lib\site-packages\matplotlib\axes\_base.py in _plot_args(self, tup, kwargs)
    389             x, y = index_of(tup[-1])
    390 
--> 391         x, y = self._xy_from_xy(x, y)
    392 
    393         if self.command == 'plot':

E:\python\lib\site-packages\matplotlib\axes\_base.py in _xy_from_xy(self, x, y)
    241     def _xy_from_xy(self, x, y):
    242         if self.axes.xaxis is not None and self.axes.yaxis is not None:
--> 243             bx = self.axes.xaxis.update_units(x)
    244             by = self.axes.yaxis.update_units(y)
    245 

E:\python\lib\site-packages\matplotlib\axis.py in update_units(self, data)
   1492         neednew = self.converter != converter
   1493         self.converter = converter
-> 1494         default = self.converter.default_units(data, self)
   1495         if default is not None and self.units is None:
   1496             self.set_units(default)

E:\python\lib\site-packages\matplotlib\category.py in default_units(data, axis)
    113         # default_units->axis_info->convert
    114         if axis.units is None:
--> 115             axis.set_units(UnitData(data))
    116         else:
    117             axis.units.update(data)

E:\python\lib\site-packages\matplotlib\category.py in __init__(self, data)
    179         self._counter = itertools.count()
    180         if data is not None:
--> 181             self.update(data)
    182 
    183     @staticmethod

E:\python\lib\site-packages\matplotlib\category.py in update(self, data)
    216             # OrderedDict just iterates over unique values in data.
    217             if not isinstance(val, (str, bytes)):
--> 218                 raise TypeError("{val!r} is not a string".format(val=val))
    219             if convertible:
    220                 # this will only be called so long as convertible is True.

TypeError: ('PM2.5', 'count', '00:00') is not a string
  • 2
    This question, in its current state, is difficult to answer. pd.read_image does not exist so it is very difficult to incorporate your dataset into a clean workspace and reproduce the issue. Please take a look at [How to make good reproducible pandas examples](https://stackoverflow.com/q/20109391/15497888) for a better understanding of the type of information expected in these types of questions. Generally we expect to be able to copy a continuous block of code into a clean workspace and be able to reproduce the issue. – Henry Ecker Jun 27 '21 at 16:37
  • Plus, please post your full traceback when asking questions about Python errors. – Iguananaut Jun 27 '21 at 16:51
  • Hey @Iguananaut ,@Henry Ecker I've edited the question for better understanding –  Jun 27 '21 at 19:31
  • The cause of the error is that the y-value of some data is set to the index of all data. So please fix it as follows. `x = data[(data.index.get_level_values(0) == 'NOx') & (data.index.get_level_values(1) == 'mean')];ax.plot(x, data['NOx']['mean'], 'g', linewidth=2.0)` – r-beginners Jun 28 '21 at 03:31
  • Hey @ r-beginners this worked perfectly! Thanks for the answer! –  Jun 28 '21 at 06:54

0 Answers0