python - 如何向 matplotlib.pyplot.matshow 绘图添加标签和标题

标签 python pandas matplotlib

预先感谢您的帮助! (下面提供了代码)

我正在绘制时间序列热图,并且正在努力向 x 轴、y 轴添加标签并分配标题。我尝试使用 xlabel = 'Days in a Year' 并收到以下语法错误:

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

当代码中没有 xlabel = 'Hello' 时,我不会收到此错误。如何正确添加这些标签? 它应该看起来像这样:

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');

错误

    ---------------------------------------------------------------------------
    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'

最佳答案

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

关于python - 如何向 matplotlib.pyplot.matshow 绘图添加标签和标题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64056507/

相关文章:

python列表转换

python - 求和一列值,包括 Python 中的字母

graphics - 如何在matplotlib的散点图中设置点的边框颜色?

python - 相当于matplotlib中matlab的imagesc?

python - lxml xpath 无法导入名称 etree

python - 如何使用 sel 更改 xarray.DataArray 中的单个条目?

python - Pandas - 通过在另一个数据框中查找来替换值

python - 基于包含值的其他列复制行,然后返回具有拆分列值的行

python - 如何在堆叠条形图显示中抑制零

python - Seaborn 热图不断在数据集上循环添加颜色条