Cannot change default colormap in matplotlib - python

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?

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]])

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'])

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.

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'

Related

How to get visible bars on a histogram/distribution plot? [duplicate]

While doing some practice problems using seaborn and a Jupyter notebook, I realized that the distplot() graphs did not have the darker outlines on the individual bins that all of the sample graphs in the documentation have. I tried creating the graphs using Pycharm and noticed the same thing. Thinking it was a seaborn problem, I tried some hist() charts using matplotlib, only to get the same results.
import matplotlib.pyplot as plt
import seaborn as sns
titanic = sns.load_dataset('titanic')
plt.hist(titanic['fare'], bins=30)
yielded the following graph:
Finally I stumbled across the 'edgecolor' parameter on the plt.hist() function, and setting it to black did the trick. Unfortunately I haven't found a similar parameter to use on the seaborn distplot() function, so I am still unable to get a chart that looks like it should.
I looked into changing the rcParams in matplotlib, but I have no experience with that and the following script I ran seemed to do nothing:
import matplotlib as mpl
mpl.rcParams['lines.linewidth'] = 1
mpl.rcParams['lines.color'] = 'black'
mpl.rcParams['patch.linewidth'] = 1
mpl.rcParams['patch.edgecolor'] = 'black'
mpl.rcParams['axes.linewidth'] = 1
mpl.rcParams['axes.edgecolor'] = 'black'
I was just kind of guessing at the value I was supposed to change, but running my graphs again showed no changes.
I then attempted to go back to the default settings using mpl.rcdefaults()
but once again, no change.
I reinstalled matplotlib using conda but still the graphs look the same. I am running out of ideas on how to change the default edge color for these charts. I am running the latest versions of Python, matplotlib, and seaborn using the Conda build.
As part of the update to matplotlib 2.0 the edges on bar plots are turned off by default. However, you may use the rcParam
plt.rcParams["patch.force_edgecolor"] = True
to turn the edges on globally.
Probably the easiest option is to specifically set the edgecolor when creating a seaborn plot, using the hist_kws argument,
ax = sns.distplot(x, hist_kws=dict(edgecolor="k", linewidth=2))
For matplotlib plots, you can directly use the edgecolor or ec argument.
plt.bar(x,y, edgecolor="k")
plt.hist(x, edgecolor="k")
Equally, for pandas plots,
df.plot(kind='hist',edgecolor="k")
A complete seaborn example:
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
x = np.random.randn(100)
ax = sns.distplot(x, hist_kws=dict(edgecolor="k", linewidth=2))
plt.show()
As of Mar, 2021 :
sns.histplot(data, edgecolor='k', linewidth=2)
work.
Using hist_kws=dict(edgecolor="k", linewidth=2) gave an error:
AttributeError: 'PolyCollection' object has no property 'hist_kws'
Using the available styles in seaborn could also solve your problem.
Available styles in seaborn are :
ticks
dark
darkgrid
white
whitegrid

How do I change the default colormap for pyplot?

I would like to change the default colormap for pyplots from 'viridis' to 'Dark2'.
I tried:
changing the 'image.cmap' line in the matplotlibrc file
mpl.rcParams['image.cmap'] = 'Dark2'
mpl.pyplot.set_cmap('Dark2')
pyplot.set_cmap('Dark2')
Somehow none of these attempts worked. I also tried restarting the kernel afterwards and also restartet spyder itself but nothing changed. Now Im out of ideas.
import matplotlib as mpl
from matplotlib import pyplot
mpl.rcParams['image.cmap'] = 'Dark2'
mpl.pyplot.set_cmap('Dark2')
pyplot.set_cmap('Dark2')
I am always ending up with the default colors of the viridis colormap which starts with a blueish color and 2nd on orange one. I would like to see the green color from Dark2 first and than the orange one.
Appreciate your help !
cheers, Gerrit
I don't think plt.set_cmap works for your use case. Here are two options that should.
Use Seaborn's helper:
import seaborn as sns
sns.set_palette('Dark2')
Use Maplotlib rcParams:
from cycler import cycler
from matplotlib import pyplot as plt
plt.rcParams['axes.prop_cycle'] = cycler('color', plt.get_cmap('Dark2').colors)
You can use matplotlib.pyplot.set_cmap is the way to change the default colormap. If you run the code below, you should see the 'Dark2' colormap.
import matplotlib.pyplot as plt
import numpy as np
plt.set_cmap('Dark2')
plt.imshow(np.random.random((20, 20)))
plt.colorbar()
plt.show()

No outlines on bins of Matplotlib histograms or Seaborn distplots

While doing some practice problems using seaborn and a Jupyter notebook, I realized that the distplot() graphs did not have the darker outlines on the individual bins that all of the sample graphs in the documentation have. I tried creating the graphs using Pycharm and noticed the same thing. Thinking it was a seaborn problem, I tried some hist() charts using matplotlib, only to get the same results.
import matplotlib.pyplot as plt
import seaborn as sns
titanic = sns.load_dataset('titanic')
plt.hist(titanic['fare'], bins=30)
yielded the following graph:
Finally I stumbled across the 'edgecolor' parameter on the plt.hist() function, and setting it to black did the trick. Unfortunately I haven't found a similar parameter to use on the seaborn distplot() function, so I am still unable to get a chart that looks like it should.
I looked into changing the rcParams in matplotlib, but I have no experience with that and the following script I ran seemed to do nothing:
import matplotlib as mpl
mpl.rcParams['lines.linewidth'] = 1
mpl.rcParams['lines.color'] = 'black'
mpl.rcParams['patch.linewidth'] = 1
mpl.rcParams['patch.edgecolor'] = 'black'
mpl.rcParams['axes.linewidth'] = 1
mpl.rcParams['axes.edgecolor'] = 'black'
I was just kind of guessing at the value I was supposed to change, but running my graphs again showed no changes.
I then attempted to go back to the default settings using mpl.rcdefaults()
but once again, no change.
I reinstalled matplotlib using conda but still the graphs look the same. I am running out of ideas on how to change the default edge color for these charts. I am running the latest versions of Python, matplotlib, and seaborn using the Conda build.
As part of the update to matplotlib 2.0 the edges on bar plots are turned off by default. However, you may use the rcParam
plt.rcParams["patch.force_edgecolor"] = True
to turn the edges on globally.
Probably the easiest option is to specifically set the edgecolor when creating a seaborn plot, using the hist_kws argument,
ax = sns.distplot(x, hist_kws=dict(edgecolor="k", linewidth=2))
For matplotlib plots, you can directly use the edgecolor or ec argument.
plt.bar(x,y, edgecolor="k")
plt.hist(x, edgecolor="k")
Equally, for pandas plots,
df.plot(kind='hist',edgecolor="k")
A complete seaborn example:
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
x = np.random.randn(100)
ax = sns.distplot(x, hist_kws=dict(edgecolor="k", linewidth=2))
plt.show()
As of Mar, 2021 :
sns.histplot(data, edgecolor='k', linewidth=2)
work.
Using hist_kws=dict(edgecolor="k", linewidth=2) gave an error:
AttributeError: 'PolyCollection' object has no property 'hist_kws'
Using the available styles in seaborn could also solve your problem.
Available styles in seaborn are :
ticks
dark
darkgrid
white
whitegrid

Seaborn: Specify an exact color

You can specify a color for plots, but Seaborn will mute the color a bit during plotting. Is there a way to turn off this behavior?
Example:
import matplotlib
import seaborn as sns
import numpy as np
# Create some data
np.random.seed(0)
x = np.random.randn(100)
# Set the Seaborn style
sns.set_style('white')
# Specify a color for plotting
current_palette = matplotlib.colors.hex2color('#86b92e')
# Make a plot
g = sns.distplot(x, color=current_palette)
# Show what the color should look like
sns.palplot(current_palette)
I have tried several ways of specifying the color and all available styles in Seaborn, but nothing has worked. I am using iPython notebook and Python 2.7.
It is not using a muted color, its using an alpha/transparency value as part of the default.
Two answers referencing ways to modify matplotlib object transparency:
https://stackoverflow.com/a/4708018
https://stackoverflow.com/a/24549558
seaborn.distplot allows you to pass different parameters for styling (*_kws). Each plot function has it's own parameters and are therefor prefixed by the name of the plot. Eg. histogram has hist_kws. [distplot Reference]
Because the histogram plot is located in matplotlib, we'd have to look at the keyword parameters we can pass. Like you already figured out, you can pass the 'alpha' keyword parameter to get rid of the transparancy of the lines. See reference for more arguments (kwargs section). [pyplot Reference]

set IPython Notebook inline plots background not transparent

In IPython Notebook 3, when I use the Inline matplotlib backend, the png figures in the browser have a transparent background.
How do I set it to white instead?
Minimal example:
%matplotlib inline
import matplotlib.pyplot as plt
plt.plot([1,2])
Right click and save the image, the image has a transparent background, I would like it to be white instead.
Update
Tried to set figure.facecolor in matplotlibrc but it still displays a transparent png:
import matplotlib
print("facecolor before:")
print(matplotlib.rcParams["figure.facecolor"])
%matplotlib inline
import matplotlib.pyplot as plt
plt.plot([1,2])
print("facecolor after:")
print(matplotlib.rcParams["figure.facecolor"])
This code gives as output:
facecolor before:
1.0
facecolor after:
(1, 1, 1, 0)
Assuming the area that was transparent is everything surrounding the ax (subplot) you can try this:
%matplotlib inline
import matplotlib.pyplot as plt
fig, ax = plt.subplots(facecolor='w')
ax.plot([1,2])
If you want to have white background in figures permanently you need to modify you matplotlibrc file (located in your home folder under .matplotlib\) changing these parameters:
figure.facecolor = 1
But you can always save you figure automatically with any background you want (independent from what it was when the figure was created) by passing facecolor:
fig.savefig('filename.png', facecolor='w', transparent=False)
Another option, instead of setting facecolor, is to use the seaborn package.
Just run:
import seaborn as sns
it automatically sets the plot background and also gives better default colors for matplotlib.

Categories