I am having trouble making a custom range for a legend in ContourPlot
since the legend doesn't "talk" to the PlotRange
and adjust its scale accordingly. How do I go about fixing this?
As an explicit example consider the following. If I run ContourPlot
with an automatic legend I get the right scaling:
ContourPlot[x y , {x, 0, 2}, {y, 0, 2}, PlotLegends->Automatic,
ColorFunction ->"BlueGreenYellow"]
But if I use a custom legend range then the legend no longer corresponds to the image:
ContourPlot[x y , {x, 0, 2}, {y, 0, 2},
PlotLegends -> BarLegend[{"BlueGreenYellow", {0, 10}}]
How do I get the plot to use the same scale as the legend?
Answer
This was more involved than I expected. First, you need to set the ColorFunction
to encompass the full range,
ColorData[{"BlueGreenYellow", {0, 10}}]
Interestingly, I did not know about that form of ColorData
until earlier this week, so I recommend reading through the Details section closely. Now, to use this within ContourPlot
, you need to set
ColorFunctionScaling -> False
otherwise ContourPlot
will rescale everything. As to the legend, you need to specify both the contour range, like you were doing, and the number of contours to force it to use the range correctly,
BarLegend[{Automatic, {0, 10}}, 20]
Note the use of Automatic
, the color function is automatically passed to the legend, so you do not to add it again. The range is necessary because the legend is only passed the range present in the plot itself. Lastly, the number of contours has to be large enough for BarLegend
to use the full range, and 20 works here. All together, this is
ContourPlot[x y, {x, 0, 2}, {y, 0, 2},
PlotLegends -> BarLegend[{Automatic, {0, 10}}, 20],
ColorFunction -> ColorData[{"BlueGreenYellow", {0, 10}}],
ColorFunctionScaling -> False
]
Comments
Post a Comment