Make the size of a heatmap bigger with seaborn

Question:

I create a heatmap with seaborn

df1.index = pd.to_datetime(df1.index)
df1 = df1.set_index('TIMESTAMP')
df1 = df1.resample('30min').mean()
ax = sns.heatmap(df1.iloc[:, 1:6:], annot=True, linewidths=.5)

But the probleme is when there is lot of data in the dataframe the heatmap will be too small and the value inside begin not clear like in the attached image.

How can I change the size of the heatmap to be more bigger ?
Thank youenter image description here

EDIT

I try :

df1.index = pd.to_datetime(df1.index)
fig, ax = plt.subplots(figsize=(10,10))         # Sample figsize in inches
sns.heatmap(df1.iloc[:, 1:6:], annot=True, linewidths=.5, ax=ax)
df1 = df1.set_index('TIMESTAMP')
df1 = df1.resample('1d').mean()
ax = sns.heatmap(df1.iloc[:, 1:6:], annot=True, linewidths=.5)

But I get this error :

KeyError                                  Traceback (most recent call last)
C:UsersDemonstratorAnaconda3libsite-packagespandasindexesbase.py in get_loc(self, key, method, tolerance)
   1944             try:
-> 1945                 return self._engine.get_loc(key)
   1946             except KeyError:

pandasindex.pyx in pandas.index.IndexEngine.get_loc (pandasindex.c:4154)()

pandasindex.pyx in pandas.index.IndexEngine.get_loc (pandasindex.c:4018)()

pandashashtable.pyx in pandas.hashtable.PyObjectHashTable.get_item (pandashashtable.c:12368)()

pandashashtable.pyx in pandas.hashtable.PyObjectHashTable.get_item (pandashashtable.c:12322)()

KeyError: 'TIMESTAMP'

During handling of the above exception, another exception occurred:

KeyError                                  Traceback (most recent call last)
<ipython-input-779-acaf05718dd8> in <module>()
      2 fig, ax = plt.subplots(figsize=(10,10))         # Sample figsize in inches
      3 sns.heatmap(df1.iloc[:, 1:6:], annot=True, linewidths=.5, ax=ax)
----> 4 df1 = df1.set_index('TIMESTAMP')
      5 df1 = df1.resample('1d').mean()
      6 ax = sns.heatmap(df1.iloc[:, 1:6:], annot=True, linewidths=.5)

C:UsersDemonstratorAnaconda3libsite-packagespandascoreframe.py in set_index(self, keys, drop, append, inplace, verify_integrity)
   2835                 names.append(None)
   2836             else:
-> 2837                 level = frame[col]._values
   2838                 names.append(col)
   2839                 if drop:

C:UsersDemonstratorAnaconda3libsite-packagespandascoreframe.py in __getitem__(self, key)
   1995             return self._getitem_multilevel(key)
   1996         else:
-> 1997             return self._getitem_column(key)
   1998 
   1999     def _getitem_column(self, key):

C:UsersDemonstratorAnaconda3libsite-packagespandascoreframe.py in _getitem_column(self, key)
   2002         # get column
   2003         if self.columns.is_unique:
-> 2004             return self._get_item_cache(key)
   2005 
   2006         # duplicate columns & possible reduce dimensionality

C:UsersDemonstratorAnaconda3libsite-packagespandascoregeneric.py in _get_item_cache(self, item)
   1348         res = cache.get(item)
   1349         if res is None:
-> 1350             values = self._data.get(item)
   1351             res = self._box_item_values(item, values)
   1352             cache[item] = res

C:UsersDemonstratorAnaconda3libsite-packagespandascoreinternals.py in get(self, item, fastpath)
   3288 
   3289             if not isnull(item):
-> 3290                 loc = self.items.get_loc(item)
   3291             else:
   3292                 indexer = np.arange(len(self.items))[isnull(self.items)]

C:UsersDemonstratorAnaconda3libsite-packagespandasindexesbase.py in get_loc(self, key, method, tolerance)
   1945                 return self._engine.get_loc(key)
   1946             except KeyError:
-> 1947                 return self._engine.get_loc(self._maybe_cast_indexer(key))
   1948 
   1949         indexer = self.get_indexer([key], method=method, tolerance=tolerance)

pandasindex.pyx in pandas.index.IndexEngine.get_loc (pandasindex.c:4154)()

pandasindex.pyx in pandas.index.IndexEngine.get_loc (pandasindex.c:4018)()

pandashashtable.pyx in pandas.hashtable.PyObjectHashTable.get_item (pandashashtable.c:12368)()

pandashashtable.pyx in pandas.hashtable.PyObjectHashTable.get_item (pandashashtable.c:12322)()

KeyError: 'TIMESTAMP'

EDIT

TypeError                                 Traceback (most recent call last)
<ipython-input-890-86bff697504a> in <module>()
      2 df2.resample('30min').mean()
      3 fig, ax = plt.subplots()
----> 4 ax = sns.heatmap(df2.iloc[:, 1:6:], annot=True, linewidths=.5)
      5 ax.set_yticklabels([i.strftime("%Y-%m-%d %H:%M:%S") for i in df2.index], rotation=0)

C:UsersDemonstratorAnaconda3libsite-packagesseabornmatrix.py in heatmap(data, vmin, vmax, cmap, center, robust, annot, fmt, annot_kws, linewidths, linecolor, cbar, cbar_kws, cbar_ax, square, ax, xticklabels, yticklabels, mask, **kwargs)
    483     plotter = _HeatMapper(data, vmin, vmax, cmap, center, robust, annot, fmt,
    484                           annot_kws, cbar, cbar_kws, xticklabels,
--> 485                           yticklabels, mask)
    486 
    487     # Add the pcolormesh kwargs here

C:UsersDemonstratorAnaconda3libsite-packagesseabornmatrix.py in __init__(self, data, vmin, vmax, cmap, center, robust, annot, fmt, annot_kws, cbar, cbar_kws, xticklabels, yticklabels, mask)
    165         # Determine good default values for the colormapping
    166         self._determine_cmap_params(plot_data, vmin, vmax,
--> 167                                     cmap, center, robust)
    168 
    169         # Sort out the annotations

C:UsersDemonstratorAnaconda3libsite-packagesseabornmatrix.py in _determine_cmap_params(self, plot_data, vmin, vmax, cmap, center, robust)
    202                                cmap, center, robust):
    203         """Use some heuristics to set good defaults for colorbar and range."""
--> 204         calc_data = plot_data.data[~np.isnan(plot_data.data)]
    205         if vmin is None:
    206             vmin = np.percentile(calc_data, 2) if robust else calc_data.min()

TypeError: ufunc 'isnan' not supported for the input types, and the inputs could not be safely coerced to any supported types according to the casting rule ''safe''
Asked By: Bio

||

Answers:

You could alter the figsize by passing a tuple showing the width, height parameters you would like to keep.

import matplotlib.pyplot as plt

fig, ax = plt.subplots(figsize=(10,10))         # Sample figsize in inches
sns.heatmap(df1.iloc[:, 1:6:], annot=True, linewidths=.5, ax=ax)

EDIT

I remember answering a similar question of yours where you had to set the index as TIMESTAMP. So, you could then do something like below:

df = df.set_index('TIMESTAMP')
df.resample('30min').mean()
fig, ax = plt.subplots()
ax = sns.heatmap(df.iloc[:, 1:6:], annot=True, linewidths=.5)
ax.set_yticklabels([i.strftime("%Y-%m-%d %H:%M:%S") for i in df.index], rotation=0)

For the head of the dataframe you posted, the plot would look like:

enter image description here

Answered By: Nickil Maveli

add plt.figure(figsize=(16,5)) before the sns.heatmap and play around with the figsize numbers till you get the desired size

...

plt.figure(figsize = (16,5))

ax = sns.heatmap(df1.iloc[:, 1:6:], annot=True, linewidths=.5)
Answered By: Sam Komo

I do not know how to solve this using code, but I do manually adjust the control panel at the right bottom in the plot figure, and adjust the figure size like:

f, ax = plt.subplots(figsize=(16, 12))

at the meantime until you get a matched size colobar. This worked for me.

Answered By: zhaoyang
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.