replicating R/ggplot2 colours in python

Viewed 2510

This link has R code to replicate ggplot's colours: Plotting family of functions with qplot without duplicating data

I have had a go at replicating the code in python - but the results are not right ...

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import math
import colorsys

# function to return a list of hex colour strings
def colorMaker(n=12, start=15.0/360.0, saturation=1.0, valight=0.65) :
    listOfColours = []
    for i in range(n) :
        hue = math.modf(float(i)/float(n) + start)[0]
        #(r,g,b) = colorsys.hsv_to_rgb(hue, saturation, valight)
        (r,g,b) = colorsys.hls_to_rgb(hue, valight, saturation)
        listOfColours.append( '#%02x%02x%02x' % (int(r*255), int(g*255), int(b*255)) )
    return listOfColours

# made up data
x = np.array(range(20))
d = {}
d['y1'] = pd.Series(x, index=x)
d['y2'] = pd.Series(1.5*x + 1, index=x)
d['y3'] = pd.Series(2*x + 2, index=x)
df = pd.DataFrame(d)

# plot example
plt.figure(num=1, figsize=(10,5), dpi=100) # set default image size
colours = colorMaker(n=3)
df.plot(linewidth=2.0, color=colours)
fig = plt.gcf()
fig.savefig('test.png')

The result ...

enter image description here

5 Answers

There is a builtin ggplot style in matplotlib.

Here is a sample of what colours it uses.

import matplotlib.pyplot as plt
import matplotlib.colors as mcolors
import matplotlib.patches as mpatch
ggplot_cm = plt.rcParams["axes.prop_cycle"].by_key()["color"]

fig, ax = plt.subplots()

n_rows = len(ggplot_cm)

for j, color_name in enumerate(ggplot_cm):
    # Pick text colour based on perceived luminance.
    rgba = mcolors.to_rgba_array([color_name])
    luma = 0.299 * rgba[:, 0] + 0.587 * rgba[:, 1] + 0.114 * rgba[:, 2]
    text_color = 'k' if luma[0] > 0.5 else 'w'

    col_shift = (j // n_rows)
    y_pos = j
    text_args = dict(fontsize=10, weight='bold')
    ax.add_patch(mpatch.Rectangle((0 + col_shift, y_pos), 1, 1, color=color_name))
    ax.text(0.5 + col_shift, y_pos + .7, color_name,
            color=text_color, ha='center', **text_args)

ax.set_ylim(n_rows, -1)
ax.axis('off')

enter image description here

Related