KDecker
KDecker

Reputation: 7128

Creating a color bar for a graph that does not contain a mappable?

I am trying to add a colorbar to a graph created by the Python library matplotlib that does not contain a "mappable". From what I can tell a mapable is some sort of object, such as a contour, which has discrete values on which a colormap can be mapped. Though in my case I am programmatically generating calls to plot (lines) that are not contained in a mappable object. I don't see a constructor/method for colorbar that does not assume a mappable object exists in the plot already.

My graph so far looks like (I can't seem to get an good image, but I think this works; yes its a horrible color scheme)

enter image description here

Here is a SSCCE of code to generate a graph like in the manner I am for the problem

import matplotlib.pyplot as plt
from matplotlib.colors import LinearSegmentedColormap
from matplotlib.backends.backend_pdf import PdfPages

colorDict = {'red': [(0.0, 1.0, 1.0), (1.0, 0.0, 0.0)], 'green': [(0.0, 0.0, 0.0), (1.0, 1.0, 1.0)], 'blue': [(0.0, 0.0, 1.0), (1.0, 0.0, 0.0)]}
rgColorMap = LinearSegmentedColormap('RedGreen', colorDict, 10)
seedColors = cm.get_cmap(rgColorMap, 10)

graphPdf = PdfPages('Example.pdf')
fig = plt.figure(figsize=(8.27, 11.69), dpi=100)
for lineInd in range(1, 9):
    plt.plot([x for x in range(1, 10)], [y*lineInd for y in range(1, 10)], color=seedColors(lineInd))

graphPdf.savefig(fig)
graphPdf.close()

In this case how can I create a colorbar without having a mappable object being plotted?

Is my only solution to group the data I am plotting in the loop into a mappable and then plotting after the loop has finished, or is there a way to instantiate a colorbar without some sort of mappable?

Upvotes: 2

Views: 522

Answers (1)

ImportanceOfBeingErnest
ImportanceOfBeingErnest

Reputation: 339112

You can of course create your own ScalarMappable,

sm = plt.cm.ScalarMappable(cmap=...)

which would then need to have an array mapping to colors (sm.set_array()).

import matplotlib.pyplot as plt
import matplotlib.colors
import numpy as np

colorDict = {'red': [(0.0, 1.0, 1.0), (1.0, 0.0, 0.0)], 'green': [(0.0, 0.0, 0.0), (1.0, 1.0, 1.0)], 'blue': [(0.0, 0.0, 1.0), (1.0, 0.0, 0.0)]}
rgColorMap = matplotlib.colors.LinearSegmentedColormap('RedGreen', colorDict, 10)
seedColors = plt.cm.get_cmap(rgColorMap, 10)

sm = plt.cm.ScalarMappable(cmap=seedColors)
sm.set_array(range(1, 9))
fig = plt.figure(figsize=(8.27, 11.69), dpi=100)
for lineInd in range(1, 9):
    plt.plot([x for x in range(1, 10)], [y*lineInd for y in range(1, 10)], color=seedColors(lineInd))


fig.colorbar(sm, ticks=range(1,9), boundaries=np.arange(0.5,9,1))

plt.show()

enter image description here

Upvotes: 2

Related Questions