Search code examples
pythonmatplotlibcolorbar

How to add a colorbar to pandas.plotting.parallel_coordinates?


I try to create a parallel_coordinates plot where the line color indicates the value of a signal. The output of the plot is fine:

sample plot

But I would like to add a colorbar legend to this plot to explain the meaning of the colors.

thePlot: plt.Axes = parallel_coordinates(myDataFrame, class_column=class_column, cols=plotColumns, colormap='hot')
plt.colorbar(thePlot)

Crashes with AttributeError: 'AxesSubplot' object has no attribute 'get_array', and

thePlot: plt.Axes = parallel_coordinates(myDataFrame, class_column=class_column, cols=plotColumns, colormap='hot')
plt.colorbar()

crashes with: RuntimeError: No mappable was found to use for colorbar creation. First define a mappable such as an image (with imshow) or a contour set (with contourf).

How to add a colorbar as legend?


Solution

  • parallel_coordinates creates lots of individual short lines, each with its own color. Therefore, there is no element with information to create a colorbar.

    You can create a colorbar from scratch with the same parameters:

    from matplotlib.cm import ScalarMappable
    plt.colorbar(ScalarMappable(norm=plt.Normalize(df['coloring'].min(), df['coloring'].max()), cmap='hot'), ax=thePlot)