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}}]

enter image description here

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?

  • $\begingroup$ 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? $\endgroup$ – 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}}]

enter image description here

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]

enter image description here

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.

| improve this answer | |
  • $\begingroup$ 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). $\endgroup$ – user18798 Dec 13 '15 at 23:21
  • 1
    $\begingroup$ 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. $\endgroup$ – Jason B. Dec 14 '15 at 8:26

Not the answer you're looking for? Browse other questions tagged or ask your own question.