Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

replicating R/ggplot2 colours in python

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

like image 740
Mark Graph Avatar asked Dec 09 '22 10:12

Mark Graph


2 Answers

You should check mpltools a really neat matplotlib extension. There is a ggplot style see here. E.g. (from link): enter image description here

like image 78
Jakob Avatar answered Dec 27 '22 10:12

Jakob


There has been a fair amount of talk lately about unifying efforts to build libraries on top of matplotlib that create aesthetically pleasing plots in a much more direct fashion. Currently, there are several options out there. Unfortunately, the ecosystem is heavily fragmented.

In addition to mpltools mentioned by Jakob, I'd like to point out these three:

  • Python-ggplot: http://www.github.com/yhat/ggplot; and
  • Seaborn: http://www.github.com/mwaskom/seaborn;
  • prettyplotlib: http://www.github.com/olgabot/prettyplotlib

If you're familiar with R's ggplot2 already, you should feel pretty comfortable with python-ggplot and I heartily encourage you to contribute to it. Personally, I don't think I'll ever get my head around that style of plotting API (that's a critique of myself, not ggplot). Finally, my cursory looks at Seaborn and prettyplotlib lead me to believe that they're more akin to mpltools in that they provide convenience functions that build off of matplotlib.

From the sounds of things, the pandas community at least is putting more effort into growing seaborn and ggplot. I'm personally excited by this. It's worth mentioning that all of the efforts are to build on top of -- not replace -- matplotlib. I think most folks (self included) are very grateful for the robust and general framework the MPL devs have created over the past decade.

like image 31
Paul H Avatar answered Dec 27 '22 11:12

Paul H