Skip to content Skip to sidebar Skip to footer

Matplotlib Cmap Colours Are Not In The Same Order

I'm plotting two dataframes on the same plot, together with the means of each dataset with the same cmap each dataset. However, the order of the colours in which the cmap is applie

Solution 1:

Something strange is happening, probably some kind of bug in how pandas works with matplotlib: whenever a marker is a lower case letter, it doesn't seem to obey to the given colormap, it just follows the 'prop_cycle'.

Here are two workarounds. The simplest is just to avoid all these lower case letter markers and choose different ones.

Another workaround, is to explicitly set a color cycle, and reset it when the second part is plotted. Note that cmap = plt.cm.get_cmap('viridis', 9) selects 9 equally spaced colors from the viridis colormap. If no explicit number is set, viridis has 256 colors, of which the 8 first all are very similar (dark purple). We choose 9 colors and later ignore the last one, because the yellow has too little contrast for this application. (Don't forget to leave out the cmap argument from pandas plot).

An explicit color cycle gives more control over exactly which colors are used. You can also choose e.g. cmap = plt.cm.get_cmap('Dark2') which only has darker colors with sufficient contrast towards the white background.

Here is some code to demonstrate how it could work:

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

df1 = pd.DataFrame(np.random.randint(10, 25, size=(7, 8)), columns=list('ABCDEFGH'))
df2 = pd.DataFrame(np.random.randint(30, 45, size=(7, 8)), columns=list('ABCDEFGH'))

# create a color map with 9 colors from viridis
cmap = plt.cm.get_cmap('viridis', 9)

fig, ax = plt.subplots(figsize=(8, 4))
markers = ['.', '*', '1', '2', '3', '4', '+', 'x']
# plot the first dataframe# set the prop_cycle to use 8 colors from the given colormap
ax.set_prop_cycle(color=cmap.colors[0:8])
df1.plot(style=markers, ax=ax)
df1.mean(axis=1).plot(c='red', style='--', label='M1 mean', ax=ax)

# plot the second dataframe
ax.set_prop_cycle(color=cmap.colors[0:8])
df2.plot(ax=ax, style=markers)
df2.mean(axis=1).plot(ax=ax, c='black', style='--', label='M3 mean')

plt.ylim(0, 45)
plt.xlim(-0.5, 6.2)
plt.ylabel('Average Efficiency')
plt.xticks(range(7), ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'])
# change the legend
plt.legend(title='Groups', bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0.1, ncol=2)

font = {'family': 'normal',
        'weight': 'normal',
        'size': 10}
matplotlib.rc('font', **font)
plt.tight_layout()
plt.show()

resulting plot

Post a Comment for "Matplotlib Cmap Colours Are Not In The Same Order"