2

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

Fringant
  • 525
  • 1
  • 5
  • 17
  • Possible duplicate of [how to use matplotlib's set\_cmap()?](https://stackoverflow.com/questions/27299577/how-to-use-matplotlibs-set-cmap) – Chris Sep 13 '19 at 14:33
  • Thanks! But in your link it's not the default behaviour. But it did tell me that what I need to change is not the colormap but the color cycle. When you get this, then the answer is here: https://stackoverflow.com/questions/9397944/how-to-set-the-default-color-cycle-for-all-subplots-with-matplotlib – Fringant Sep 13 '19 at 15:22

4 Answers4

1

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

Fringant
  • 525
  • 1
  • 5
  • 17
0

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.

stephen_mugisha
  • 889
  • 1
  • 8
  • 18
0

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'
Massifox
  • 4,369
  • 11
  • 31
  • Same problem. Default colormap unchanged. Does the code work for you? I'm using python 3.0 and jupyter notebook. – Fringant Sep 13 '19 at 14:27
0

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'])
Chris
  • 15,819
  • 3
  • 24
  • 37