I'm trying to get a plot to have a different colormap than the default. The dark2 colormap looks like the best thing for my data, but it's all coming out with the default colors. What am I missing?
import matplotlib
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from pylab import get_cmap
data = [{'a': 1, 'b': 1, 'c': 2, 'd': 0},{'a': 1, 'b': 1, 'c': 2, 'd': 0},
{'a': 1, 'b': 1, 'c': 1, 'd': 2},{'a': 1, 'b': 2.5, 'c': 1, 'd': 2},
{'a': 1.7, 'b': 2.1, 'c': 2, 'd': 0.2},{'a': 1.7, 'b': 2.1, 'c': 2, 'd': 0.2}]
cm = get_cmap('Dark2')
cnorm = matplotlib.colors.Normalize(vmin=0, vmax=len(data))
smap = matplotlib.cm.ScalarMappable(norm=cnorm, cmap=cm)
_fig, ax = plt.subplots(1, 1, figsize=(18, 8))
for lx in range(len(ax.axes.lines)):
ax.axes.lines[lx].set_color(smap.to_rgba(lx))
print('setting color for %i to %s' % (lx, smap.to_rgba(lx)))
frm = pd.DataFrame(data)
frm.plot(ax=ax)
plt.show()
You're setting the colors on an empty list. Just move the code around and you're set:
import matplotlib
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
%matplotlib inline
data = [
{'a': 1, 'b': 1, 'c': 2, 'd': 0},
{'a': 1, 'b': 1, 'c': 2, 'd': 0},
{'a': 1, 'b': 1, 'c': 1, 'd': 2},
{'a': 1, 'b': 2.5, 'c': 1, 'd': 2},
{'a': 1.7, 'b': 2.1, 'c': 2, 'd': 0.2},
{'a': 1.7, 'b': 2.1, 'c': 2, 'd': 0.2}
]
cm = matplotlib.cm.Dark2
cnorm = matplotlib.colors.Normalize(vmin=0, vmax=len(data))
smap = matplotlib.cm.ScalarMappable(norm=cnorm, cmap=cm)
_fig, ax = plt.subplots(1, 1, figsize=(18, 8))
frm = pd.DataFrame(data)
frm.plot(ax=ax, legend=False) # legend=False b/c we haven't tweaked colors yet
for lx in range(len(ax.axes.lines)):
ax.axes.lines[lx].set_color(smap.to_rgba(lx))
# now this will actually print something
print('setting color for %i to %s' % (lx, smap.to_rgba(lx)))
ax.legend() # and now do the legend
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments