# ListDensityPlot — bar legend colors inconsistent with plot value coloring [duplicate]

I want to make a ListDensityPlot of an array of values that happen to be 1.

To mimic this, use:

testdata = Table[{i, j, 1.}, {i, 10}, {j, 10}] // Flatten[#, 1] &;

ListDensityPlot[testdata, ColorFunction -> "TemperatureMap",
PlotLegends -> BarLegend[{"TemperatureMap", {-1, 1}}],
PlotRange -> {{1, 10}, {1, 10}, 1 {-1, 1}}]


Even after explicitly setting the legend range and the plot range to the same values, the result ends up as -1 instead of 1. Why and how do I solve this?

• How do you want the legend to look like? You want the color blue to be at 1? What color would the red be at? Or are you wanting the plot to be red instead, matching the current color bar? – Jason B. Dec 10 '15 at 11:22

I assume the issue is that the value in the density plot doesn't match the legend, so there are a couple ways to do this. First, just use Automatic for the legend,

ListDensityPlot[testdata, ColorFunction -> "TemperatureMap",
PlotLegends -> Automatic, PlotRange -> {{1, 10}, {1, 10}, 1 {-1, 1}}]


Now it matches. But if you really want the legend to go from -1 to 1, then you can manually "rescale" the data and then plot with ColorFunctionScaling -> False,

colorfunc[x_] := ColorData["TemperatureMap"][Rescale[x, {-1, 1}]];
ListDensityPlot[testdata, ColorFunction -> colorfunc,
PlotLegends -> BarLegend[{colorfunc[#]&, {-1, 1}}],
PlotRange -> {{1, 10}, {1, 10}, 1 {-1, 1}},
ColorFunctionScaling -> False]


Now in this particular example, you can even skip the rescaling since you are mapping a value of 1 to a value of 1. But if your constant value were any other value that wouldn't work, so this is the best way to accomplish it.

• I noticed that the distribution of colors (most notably the white spot in the spectrum) is shifted, with white now having a value of 0.5. Using your method, I tried the same with the value 0.25, but then I get a yellow/beige plane. Your answer should therefore contain an extra range in the Rescale function (the {ymin,ymax} argument). – user18798 Dec 13 '15 at 23:21
• Sorry about that, noticed it just as I was leaving work on Friday night. I couldn't get it to work using the extra argument on Rescale, but by providing the right color function to Barlegend. The color bar and plot should be consistent now. – Jason B. Dec 14 '15 at 8:26