gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 08:51:58 24 4
gpt4 key购买 nike

预先感谢您的帮助! (代码在下面提供)
我正在绘制时间序列热图,并且正在努力向 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'

最佳答案

  • 使用 .set_title .set_label 使用和绘制时 axes .
  • xlabel , ylabeltitle只是 pandas.DataFrame.plot 的绘图函数内的参数,不适用于 matplotlib.pyplot.matshow

  • 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/

    24 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com