Fringant
Fringant

Reputation: 555

Cannot change default colormap in matplotlib

I am trying to set the default colormap (not just the color of a specific plot) for matplotlib in my jupyter notebook (Python 3). I found the commands: plt.set_cmap("gray") and mpl.rc('image', cmap='gray'), that should set the default colormap to gray, but both commands are just ignored during execution and I still get the old colormap.

I tried these two codes:

import matplotlib as mpl
mpl.rc('image', cmap='gray')
plt.hist([[1,2,3],[4,5,6]])

import matplotlib.pyplot as plt
plt.set_cmap("gray")
plt.hist([[1,2,3],[4,5,6]])

They should both generate a plot with gray tones. However, the histogram has colors, which correspond to the first two colors of the default colormap. What am I not getting? myresultofbothcodes

Upvotes: 2

Views: 2921

Answers (4)

Fringant
Fringant

Reputation: 555

Thanks to the comment of Chris, I found the issue, it's not the default colormap that I need to change but the default color cycle. it's described here: How to set the default color cycle for all subplots with matplotlib?

import matplotlib as mpl
import matplotlib.pyplot as plt
from cycler import cycler

# Set the default color cycle
colors=plt.cm.gray(np.linspace(0,1,3))
mpl.rcParams['axes.prop_cycle'] = mpl.cycler(color=colors)
plt.hist([[1,2,3],[4,5,6]]) 

enter image description here

Upvotes: 1

Paul Legrand
Paul Legrand

Reputation: 1

If you are using a version of matplotlib between prio and 2.0 you need to use rcParams (still working in newer versions):

import matplotlib.pyplot as plt

plt.rcParams['image.cmap'] = 'gray'

Upvotes: 0

stephen_mugisha
stephen_mugisha

Reputation: 897

You can make use of the color argument in matplotlib plot function.

import matplotlib.pyplot as plt
plt.hist([[1,2,3],[4,5,6]], color=['gray','gray'])

with this method you have to specify the color scheme for each dataset hence an array of colors as I have put it above.

Upvotes: 0

Chris
Chris

Reputation: 16162

Since you have two data sets your are passing, you'll need to specify two colors.

plt.hist([[1,2,3],[4,5,6]], color=['black','purple'])

Upvotes: 0

Related Questions