2

Thank you in advance for your help! (The code is provided below)

I am plotting a time-series heatmap and I am struggling to add labels to the x axis, y axis, and assign a title. I have tried using xlabel = 'Days in a year' and I get this syntax error:

  AttributeError: 'AxesImage' object has no property 'xlabel'

I do not get this error when xlabel = 'Hello' is not in the code. How do I add these labels correctly? It should look somethine like this:

enter image description here

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt

# links to Minot data if you want to pull from the web
url1 = 'https://raw.githubusercontent.com/the-datadudes/deepSoilTemperature/master/minotDailyAirTemp.csv'

# load the data into a DataFrame, not a Series
# parse the dates, and set them as the index
# replace minotDailyAirTemp.csv with url if pulling from the web
df1 = pd.read_csv(url1, parse_dates=['Date'], index_col=['Date'])

# groupby year and aggregate Temp into a list
dfg1 = df1.groupby(df1.index.year).agg({'Temp': list})

# create a wide format dataframe with all the temp data expanded
df1_wide = pd.DataFrame(dfg1.Temp.tolist(), index=dfg1.index)


# adding the data between 1990/01/01 -/04/23 and delete the 29th of Feb
rng = pd.date_range(start='1990-01-01', end='1990-04-23', freq='D')
df = pd.DataFrame(index= rng)
df.index = pd.to_datetime(df.index)
df['Temp'] = np.NaN
frames = [df, df1]
result = pd.concat(frames)
result = result[~((result.index.month == 2) & (result.index.day == 29))]

dfg1 = result.groupby(result.index.year).agg({'Temp': list})
df1_wide = pd.DataFrame(dfg1['Temp'].tolist(), index=dfg1.index)

# Setting all leftover empty fields to the average of that time in order to fill in the gaps
df1_wide = df1_wide.apply(lambda x: x.fillna(x.mean()),axis=0)

# ploting the data

fig, (ax1) = plt.subplots(ncols=1, figsize=(20, 5))
ax1.matshow(df1_wide, interpolation=None, aspect='auto');

Error

    ---------------------------------------------------------------------------
    AttributeError                            Traceback (most recent call last)
    <ipython-input-289-fd46af2ae9bf> in <module>
         36 
         37 fig, (ax1) = plt.subplots(ncols=1, figsize=(20, 5))
    ---> 38 ax1.matshow(df1_wide, interpolation=None, aspect='auto', xlabel = 'Hello');
     39 

    ~\anaconda3\lib\site-packages\matplotlib\axes\_axes.py in matshow(self, Z, **kwargs)
       7789               'aspect': 'equal',          # (already the imshow default)
       7790               **kwargs}
    -> 7791         im = self.imshow(Z, **kw)
       7792         self.title.set_y(1.05)
       7793         self.xaxis.tick_top()

    ~\anaconda3\lib\site-packages\matplotlib\__init__.py in inner(ax, data, *args, **kwargs)
       1563     def inner(ax, *args, data=None, **kwargs):
       1564         if data is None:
    -> 1565             return func(ax, *map(sanitize_sequence, args), **kwargs)
       1566 
       1567         bound = new_sig.bind(ax, *args, **kwargs)

    ~\anaconda3\lib\site-packages\matplotlib\cbook\deprecation.py in wrapper(*args, **kwargs)
        356                 f"%(removal)s.  If any parameter follows {name!r}, they "
        357                 f"should be pass as keyword, not positionally.")
    --> 358         return func(*args, **kwargs)
        359 
        360     return wrapper

    ~\anaconda3\lib\site-packages\matplotlib\cbook\deprecation.py in wrapper(*args, **kwargs)
        356                 f"%(removal)s.  If any parameter follows {name!r}, they "
        357                 f"should be pass as keyword, not positionally.")
    --> 358         return func(*args, **kwargs)
        359 
        360     return wrapper

    ~\anaconda3\lib\site-packages\matplotlib\axes\_axes.py in imshow(self, X, cmap, norm, aspect, interpolation, alpha, vmin, vmax, origin, extent, shape, filternorm, filterrad, imlim, resample, url, **kwargs)
       5620             aspect = rcParams['image.aspect']
       5621         self.set_aspect(aspect)
    -> 5622         im = mimage.AxesImage(self, cmap, norm, interpolation, origin, extent,
       5623                               filternorm=filternorm, filterrad=filterrad,
       5624                               resample=resample, **kwargs)

    ~\anaconda3\lib\site-packages\matplotlib\image.py in __init__(self, ax, cmap, norm, interpolation, origin, extent, filternorm, filterrad, resample, **kwargs)
        888         self._extent = extent
        889 
    --> 890         super().__init__(
        891             ax,
        892             cmap=cmap,

    ~\anaconda3\lib\site-packages\matplotlib\image.py in __init__(self, ax, cmap, 
norm, interpolation, origin, filternorm, filterrad, resample, **kwargs)
        259         self._imcache = None
        260 
    --> 261         self.update(kwargs)
        262 
        263     def __getstate__(self):

    ~\anaconda3\lib\site-packages\matplotlib\artist.py in update(self, props)
       1004 
       1005         with cbook._setattr_cm(self, eventson=False):
    -> 1006             ret = [_update_property(self, k, v) for k, v in 
    props.items()]
       1007 
       1008         if len(ret):

    ~\anaconda3\lib\site-packages\matplotlib\artist.py in <listcomp>(.0)
       1004 
       1005         with cbook._setattr_cm(self, eventson=False):
    -> 1006             ret = [_update_property(self, k, v) for k, v in 
    props.items()]
       1007 
       1008         if len(ret):

    ~\anaconda3\lib\site-packages\matplotlib\artist.py in _update_property(self, k, v)
        999                 func = getattr(self, 'set_' + k, None)
       1000                 if not callable(func):
    -> 1001                     raise AttributeError('{!r} object has no property 
    {!r}'
       1002                                          .format(type(self).__name__, k))
       1003                 return func(v)

    AttributeError: 'AxesImage' object has no property 'xlabel'
1

1 Answer 1

3
fig, (ax1) = plt.subplots(ncols=1, figsize=(10, 5))
ax1.matshow(df1_wide, interpolation=None, aspect='auto')

# add the title and label
ax1.set_title('Blah')
ax1.set_ylabel('Blah2')

# alternatively use just
ax1.set(title='Blah', ylabel='Blah2')

enter image description here

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.