Change the default colormap in Matplotlib [duplicate] - matplotlib

How can I set a default set of colors for plots made with matplotlib? I can set a particular color map like this
import numpy as np
import matplotlib.pyplot as plt
fig=plt.figure(i)
ax=plt.gca()
colormap = plt.get_cmap('jet')
ax.set_color_cycle([colormap(k) for k in np.linspace(0, 1, 10)])
but is there some way to set the same set of colors for all plots, including subplots?

Sure! Either specify axes.color_cycle in your .matplotlibrc file or set it at runtime using matplotlib.rcParams or matplotlib.rc.
As an example of the latter:
import matplotlib.pyplot as plt
import matplotlib as mpl
import numpy as np
# Set the default color cycle
mpl.rcParams['axes.prop_cycle'] = mpl.cycler(color=["r", "k", "c"])
x = np.linspace(0, 20, 100)
fig, axes = plt.subplots(nrows=2)
for i in range(10):
axes[0].plot(x, i * (x - 10)**2)
for i in range(10):
axes[1].plot(x, i * np.cos(x))
plt.show()

Starting from matplotlib 1.5, mpl.rcParams['axes.color_cycle'] is deprecated. You should use axes.prop_cycle:
import matplotlib as mpl
mpl.rcParams['axes.prop_cycle'] = mpl.cycler(color=["r", "#e94cdc", "0.7"])

In the version of 2.1.0, the below works for me, using set_prop_cycle and module cycler
from cycler import cycler
custom_cycler = (cycler(color=['r','b','m','g']))
ax.set_prop_cycle(custom_cycler)
you can add additional line attribute
custom_cycler = (cycler(color=['r','b','m','g']) + cycler(lw=[1,1,1,2]))
'ax' comes from ax=plt.axes() or any axes generator

Related

Matplotlib adjust inset_axes based on loc parameter instead of bbox?

I'm using inset_axes() to control the placement of my colorbar legend. The label hangs off the plot just a little bit. Is there a way to just nudge it over without having to do bbox_to_anchor()? Some way to do an offset from the loc parameter? I do want to keep it in the lower left.
import pandas as pd
%matplotlib inline
import matplotlib.pyplot as plt
import matplotlib.colors as mcolors
from mpl_toolkits.axes_grid1.inset_locator import inset_axes
set1 = ax2.scatter(df.x, df.y,
edgecolors = 'none',
c = df.recommended_net_preferred_for_analysis_meters,
norm = mcolors.LogNorm(), cmap='jet')
cbaxes = inset_axes(ax2, width="30%", height="3%", loc=3)
plt.colorbar(set1, cax=cbaxes, format = '%1.2f', orientation='horizontal')
cbaxes.xaxis.set_ticks_position("top")

Making sure 0 gets white in a RdBu colorbar

I create a heatmap with the following snippet:
import numpy as np
import matplotlib.pyplot as plt
d = np.random.normal(.4,2,(10,10))
plt.imshow(d,cmap=plt.cm.RdBu)
plt.colorbar()
plt.show()
The result is plot below:
Now, since the middle point of the data is not 0, the cells in which the colormap has value 0 are not white, but rather a little reddish.
How do I force the colormap so that max=blue, min=red and 0=white?
Use a DivergingNorm.
Note: From matplotlib 3.2 onwards DivergingNorm is renamed to TwoSlopeNorm.
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.colors as mcolors
d = np.random.normal(.4,2,(10,10))
norm = mcolors.DivergingNorm(vmin=d.min(), vmax = d.max(), vcenter=0)
plt.imshow(d, cmap=plt.cm.RdBu, norm=norm)
plt.colorbar()
plt.show()
A previous SO post (Change colorbar gradient in matplotlib) wanted a solution for a more complicated situation, but one of the answers talked about the MidpointNormalize subclass in the matplotlib documentation. With that, the solution becomes:
import matplotlib as mpl
import numpy as np
import matplotlib.pyplot as plt
class MidpointNormalize(mpl.colors.Normalize):
## class from the mpl docs:
# https://matplotlib.org/users/colormapnorms.html
def __init__(self, vmin=None, vmax=None, midpoint=None, clip=False):
self.midpoint = midpoint
super().__init__(vmin, vmax, clip)
def __call__(self, value, clip=None):
# I'm ignoring masked values and all kinds of edge cases to make a
# simple example...
x, y = [self.vmin, self.midpoint, self.vmax], [0, 0.5, 1]
return np.ma.masked_array(np.interp(value, x, y))
d = np.random.normal(.4,2,(10,10))
plt.imshow(d,cmap=plt.cm.RdBu,norm=MidpointNormalize(midpoint=0))
plt.colorbar()
plt.show()
Kudos to Joe Kington for writing the subclass, and to Rutger Kassies for pointing out the answer.

matplotlib adding string to a an axis

import matplotlib.pyplot as plt
import numpy as np
ydata = [55,60,65,70,75,80]
xdata = [1,2,3,4,5,6]
plt.plot(xdata, ydata)
set(plt.gca,'XTickLabel',{'Jan','Feb','Mar','April','May','June'})
plt.show()
I am using matplotlib and trying to add text values to appear on the x axis.
I have tried to use the following code but get the following error message
set(plt.gca,'XTickLabel',
{'Jan','Feb','Mar','April','May','June'})
TypeError: set expected at most 1 arguments, got 3 I am not sure what this
is referring get current access I have set the value
Sets are a Python data structure, it has nothing to do with what you want here, you only need to use ax.set_xticklabels and ax.set_xticks to ensure all of them show in the plot:
import matplotlib.pyplot as plt
import numpy as np
fig, ax = plt.subplots()
ydata = [55,60,65,70,75,80]
xdata = [1,2,3,4,5,6]
ax.set_xticks(xdata)
ax.set_xticklabels(['Jan','Feb','Mar','April','May','June'])
plt.plot(xdata, ydata)
plt.show()

Working with ipywidgets and images [duplicate]

I am trying to generate an interactive plot that depends on widgets.
The problem I have is that when I change parameters using the slider, a new plot is done after the previous one, instead I would expect only one plot changing according to the parameters.
Example:
from ipywidgets import interact, interactive, fixed, interact_manual
import ipywidgets as widgets
import matplotlib.pyplot as plt
%matplotlib inline
import numpy as np
def plot_func(freq):
x = np.linspace(0, 2*np.pi)
y = np.sin(x * freq)
plt.plot(x, y)
interact(plot_func, freq = widgets.FloatSlider(value=7.5,
min=1,
max=5.0,
step=0.5))
After moving the slider to 4.0, I have:
while I just want one figure to change as I move the slider.
How can I achieve this?
(I am using Python 2.7, matplotlib 2.0 and I have just updated notebook and jupyter to the latest version. let me know if further info is needed.)
As you want to change the figure, instead of creating a new one, may I suggest the following way:
Use an interactive backend; %matplotlib notebook
Update the line in the plot, instead of drawing new ones.
So the code could look something like this:
%matplotlib notebook
from ipywidgets import *
import numpy as np
import matplotlib.pyplot as plt
x = np.linspace(0, 2 * np.pi)
fig = plt.figure()
ax = fig.add_subplot(1, 1, 1)
line, = ax.plot(x, np.sin(x))
def update(w = 1.0):
line.set_ydata(np.sin(w * x))
fig.canvas.draw_idle()
interact(update);
Alternatively you may use plt.show() as in this answer.
This is an issue (?) introduced in the last version of jupyter and/or ipywidgets. One workaround I found was to add the line plt.show() at the end of plot_func.
For completion, here is an answer that makes use of more than one slider bar and sets the default parameters as well as the interval lengths.
%matplotlib notebook
from ipywidgets import *
import numpy as np
import matplotlib.pyplot as plt
x = np.linspace(-10, 10,100)
def f(x, A, B, C):
return A*x**2 + B*x + C
fig = plt.figure()
ax = fig.add_subplot(1, 1, 1)
line, = ax.plot(x, f(x, A=1, B=1, C=1))
def update(A = 1, B = 0, C = 0):
line.set_ydata(f(x,A,B,C))
fig.canvas.draw_idle()
interact(update, A = (-4,4,0.1), B = (-4,4,0.1), C = (-4,4,0.1));

Matplotlib Color Palette

Is it possible to change what colors Matplotlib cycles through when it is generating its own colors for a graph's lines? I'm using the pylab module.
from pylab import *
import matplotlib.cm as cm
x=[1,2,3,4]
y=[5,6,7,8]
fig1 = Figure()
plot1 = fig1.add_subplot(311)
plot1.plot(x,y)
plot2 = fig1.add_subplot(312)
plot2.plot(x,y)
plot3 = fig1.add_subplot(313)
plot3.plot(x,y)
Yes, of course. Since it accept many kinds of color definition. It's easy to define your own color map. Here I just get colors from the colormap hot
import pylab as py
import numpy as np
import matplotlib.cm as cm
a = np.arange(0,10)
py.figure()
for i in np.arange(10):
c = cm.hot(i/10.,1)
py.plot(a,i*a,color=c)
py.show()
The colors are extracted from color maps. You can use one of the predefined colormaps, or define your own.
Unfortunately there is no way to use multiple colormaps per figure, you have to do it manually:
import pylab as pl
import matplotlib.cm as cm
xval = pl.arange(0, 20, 0.2)
pl.subplot(311)
pl.plot(xval, pl.sin(xval), c=cm.summer(0))
pl.subplot(312)
pl.plot(xval, pl.cos(xval), c=cm.spring(0))
pl.subplot(313)
pl.plot(xval, pl.arctan(xval), xval, pl.fabs(xval))
pl.show()