TransWikia.com

How do I produce a BarLegend with the default coloring of a ContourPlot, using Legended?

Mathematica Asked by Neuneck on March 15, 2021

I have a series of ContourPlots that I want to compare in a GraphicsRow environment. I want to add a single legend for all three plots. Also, I really like the standard color scheme of the ContourPlot.

How can I use the standard ColorFunction from ContourPlot in a different Graphics object?

I did not find the ColorFunction that ContourPlot uses inside ColorData["Gradients"].

A minimal working example would be this line

Legended[ContourPlot[x y, {x, 0, 1}, {y, 0, 1}],
         Placed[BarLegend[{Automatic, {0, 1}}, LegendLayout -> "Row"], Below]]

Mathematica graphics

where I’m done when the BarLegend shows the same colors as the ContourPlot.

2 Answers

Legended[ContourPlot[x y, {x, 0, 1}, {y, 0, 1}],
 Placed[BarLegend[{ColorData["M10DefaultDensityGradient"], {0, 1}}, 
   LegendLayout -> "Row"], Below]]

Mathematica graphics

I found the name of the color scheme by evaluating

plot = ContourPlot[x y, {x, 0, 1}, {y, 0, 1}, PlotLegends -> Automatic]

Mathematica graphics

and looking at the expression of the result. As Legended accepts two arguments with the second being the legend, this can be easily done by running

plot[[2]] // InputForm

Correct answer by Gerli on March 15, 2021

Create your plots with the option PlotLegends -> Automatic:

threecontourplots = {plot1, plot2, plot3} = 
 ContourPlot[#, {x, 0, 1}, {y, 0, 1}, PlotLegends -> Automatic, ImageSize -> 300] & /@ 
   {x y, x + y , x};

For a legended plot object plot, you can use Part to extract the main plot (plot1[[1]]) and the legend (plot1[[2,1]]).

threecontourplots[[1, 2, 1]]

enter image description here

You can use the extracted parts with Row, GraphicsRow, Grid,GraphicsGrid as well as with Legended:

Row[Append[threecontourplots[[1, 2, 1]]]@threecontourplots[[All, 1]], 
 Spacer[10]]

enter image description here

Legended[Row[threecontourplots[[All, 1]], Spacer[10]], 
 Placed[threecontourplots[[1, 2, 1]], Right]]

enter image description here

If you use a non-default color function in ContourPlot (say, ColorFunction -> "Rainbow"`) no modification will be needed:

`enter image description here

Answered by kglr on March 15, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP