0

I have a dataframe and want to loop through all columns and add a new line to a chart, with a different colour.

This code does the trick.

variables=df.columns

colours=['b','y','r','c','k','m']
for i, j in zip(variables, colours):
    plt.plot(df[i],j+'-o',label=i)
plt.ylim(ymin=0)
plt.gcf().set_size_inches((18, 5))
plt.legend().set_visible(True)

However a different dataframe might need more colours.

Is there a way to create a list of random colours?

fred.schwartz
  • 2,023
  • 4
  • 26
  • 53
  • 2
    The difficulty is not so much creating random colors, but to make sure they are sufficiently different from each other. There are sure some answers on this however. Are they not suitable? Apart, are you sure you want random colors and not maybe colors from an existing colormap? Also note that the default color cycler of matplotlib already has 10 colors, which is more than the 6 you have in the question. – ImportanceOfBeingErnest Dec 18 '18 at 09:42
  • 1
    If you care about colors "difference", you should take a look at this https://en.wikipedia.org/wiki/HSL_and_HSV – Sylvan LE DEUNFF Dec 18 '18 at 09:52
  • 1
    Related as well: [This](https://stackoverflow.com/questions/8389636/creating-over-20-unique-legend-colors-using-matplotlib) and [this](https://stackoverflow.com/questions/4971269/how-to-pick-a-new-color-for-each-plotted-line-within-a-figure-in-matplotlib) – ImportanceOfBeingErnest Dec 18 '18 at 09:52

1 Answers1

1

From matplotlib documentation

For a greater range of colors, you have two options. You can specify the color using an html hex string, as in: color = '#eeefff'

You can generate an hexadecimal color with a function like the following

from random import randint

class Color:
    CHARS = "0123456789ABCDEF"

    @classmethod
    def random_hex(cls):
        color = "#"
        for k in range(6):
            i = randint(0, 15)
            color += cls.CHARS[i]
        return color
Sylvan LE DEUNFF
  • 682
  • 1
  • 6
  • 21