3

For extensive plotting scripts, I use matplotlibs rcParams to configure some standard plot settings for pandas DataFrames.

This works well for colors and font sizes but not for the default colormap as described here

Here's my current approach:

# -*- coding: utf-8 -*-
import pandas as pd
import numpy as np
import matplotlib
import matplotlib.pyplot as plt
from matplotlib import cm


# global plotting options
plt.rcParams.update(plt.rcParamsDefault)
matplotlib.style.use('ggplot')
plt.rcParams['lines.linewidth'] = 2.5
plt.rcParams['axes.facecolor'] = 'silver'
plt.rcParams['xtick.color'] = 'k'
plt.rcParams['ytick.color'] = 'k'
plt.rcParams['text.color'] = 'k'
plt.rcParams['axes.labelcolor'] = 'k'
plt.rcParams.update({'font.size': 10})
plt.rcParams['image.cmap'] = 'Blues'  # this doesn't show any effect


# dataframe with random data
df = pd.DataFrame(np.random.rand(10, 3))

# this shows the standard colormap
df.plot(kind='bar')
plt.show()

# this shows the right colormap
df.plot(kind='bar', cmap=cm.get_cmap('Blues'))
plt.show()

The first plot does not use the colormap via colormap (which it should normally do?): enter image description here

It only works if I pass it as an argument as in the second plot:

enter image description here

Is there any way to define the standard colormap for pandas DataFrame plots, permanently?

Thanks in advance!

Community
  • 1
  • 1
Cord Kaldemeyer
  • 6,405
  • 8
  • 51
  • 81

1 Answers1

2

There is no supported, official way to do it; you are stuck because of pandas's internal _get_standard_colors function that hardcodes the use of matplotlib.rcParams['axes.color_cycle'] and falls back to list('bgrcmyk'):

colors = list(plt.rcParams.get('axes.color_cycle',
                               list('bgrcmyk')))

There are various hacks you can use, however; one of the simplest, which works for all pandas.DataFrame.plot() calls, is to wrap pandas.tools.plotting.plot_frame:

import matplotlib
import pandas as pd
import pandas.tools.plotting as pdplot

def plot_with_matplotlib_cmap(*args, **kwargs):
    kwargs.setdefault("colormap", matplotlib.rcParams.get("image.cmap", "Blues"))
    return pdplot.plot_frame_orig(*args, **kwargs)

pdplot.plot_frame_orig = pdplot.plot_frame
pdplot.plot_frame = plot_with_matplotlib_cmap
pd.DataFrame.plot = pdplot.plot_frame

To test in a notebook:

%matplotlib inline
import pandas as pd, numpy as np
df = pd.DataFrame(np.random.random((1000,10))).plot()

...yields:

blue_plot

mtd
  • 2,224
  • 19
  • 21