# Using Legended with a black background

I'm trying to use Legended to add a legend to a plot that has a black background. I can make the background of the legend to be black as well, but there is a white border around it, which I can't figure out how to remove. How do I remove this white space?

blackFrame[legend_] :=
Framed[legend, FrameStyle -> White, Background -> Black]

Legended[
Plot[x, {x, 0, 1},
ColorFunction -> ColorData["Temperature"],
Axes -> False,
Background -> Black],
BarLegend[
{ColorData["Temperature"], {0, 1}},
LegendFunction -> blackFrame,
LabelStyle -> Directive[White]]]


• You do not make it clear what white space you are trying to remove. – m_goldberg Mar 28 '17 at 11:22

I assume that you want to export this to a raster format, like PNG.

When exporting, you can set the background colour.

leg = Legended[...];

Export["fig.png", leg, Background -> Black]


However, there may not be a sufficiently large black margin around the legend and the figure if you do this. To add it, put everything in a box using Framed:

fig = Framed[leg, Background -> Black, FrameStyle -> None]


A legend that is outside of the plot is a notebook-level object, not a Graphics-level one. This affects its behaviour. To interact with it, we need to use other notebook-level objects. Framed is the usual one to construct and control boxes.

Here, you can place everything within a box with black background and no visible border.

When you export this, it is still advisable to set a background colour:

Export["fig.png", fig, Background -> Black]


Otherwise there may be a thin white border around the black box.

• Thanks, I've never really used Framed (or Legended) before, but given that I'd just had to use it in the definition of blackFrame I should have realised it was the tool I needed. – KraZug Mar 28 '17 at 12:59
• @KraZug I do not think that this is a trivial topic. Framed seems to be very useful for controlling layouts by creating boxes. But its name suggests that it's just for adding a border. It wouldn't be my first choice if I had not seen similar usage before. There is also the thing about the different behaviour of legends when inside or outside of the graphics frame. For example, when they are outside, I think they export in the Printout environment, and everything is effectively scaled down to smaller size! stackoverflow.com/q/6093559/695132 – Szabolcs Mar 28 '17 at 13:49
• @KraZug I am sorry, my answer was not good. It is important to Export with Background -> Black. I am not sure what you were using this for, but please do not accept until you are convinced that this actually solves your problem ;-) – Szabolcs Mar 28 '17 at 17:30
• I'm using this to create a video of a set of plots, so you are correct that I need to export it. There was a thin border at the top and bottom, but I removed that in PowerPoint (and thought it was just a PowerPoint thing). Thanks for adding the extra information. – KraZug Mar 28 '17 at 18:19