G. Macia
G. Macia

Reputation: 1511

How to limit the display limits of a colorbar in matplotlib

I am plotting 3 channels of my time series measurements which are more or less centered around (-80). Missing values are filled with (-50) so that they get a bright yellow color and contrast with the rest of the plot. It has no meaning numerically. See the figure and the code below:

f, ax = plt.subplots(figsize=(12.5, 12.5))
sns.heatmap(df.loc[:, ['Ch2', 'Ch3', 'Ch1']].fillna(-50)[:270], cmap='viridis', yticklabels=27, cbar=True, ax=ax)

How can I keep the color range but limit the display scale (i.e the heatmap should stay the same but the color bar ranges only from -70 to -90)? enter image description here (Note that the question of how to Set Max value for color bar on seaborn heatmap has already been answered and it is not what I am aiming at, I want vmin and vmax to stay just as they are).

Upvotes: 1

Views: 3891

Answers (1)

ImportanceOfBeingErnest
ImportanceOfBeingErnest

Reputation: 339062

You can set the limits of the colorbar axes similar to any other axes.

ax.collections[0].colorbar.ax.set_ylim(-90,-70)

Complete example:

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

data = np.random.rand(82*3)*20-90
data[np.random.randint(1,82*3, size=20)] = np.nan
df = pd.DataFrame(data.reshape(82,3))

ax = sns.heatmap(df, vmin=-90, vmax=-50, cmap="viridis")
ax.set_facecolor("gold")
ax.collections[0].colorbar.ax.set_ylim(-90,-70)
plt.show()

enter image description here

Upvotes: 4

Related Questions