I created a column chart in my application which look like this:
As you can see the positive values are green and the negative values are red. I need to represent this in the legend. I just don't know how.
What I already tried:
I added CustomItems
to the Legend
. Here is the code:
Legend currentLegend = chart.Legends.FindByName(chart.Series[series].Legend);
if (currentLegend != null)
{
currentLegend.LegendStyle = LegendStyle.Table;
LegendItem li = new LegendItem();
li.Name = series;
li.Color = Color.Red;
li.BorderColor = Color.Transparent;
currentLegend.CustomItems.Add(li);
}
This results in the following representation:
I could live with that. But as soon as I add further series to the chart the order of the elements gets destroyed. Here is an example:
I would like to have one of the two options:
- keep the positive and negative color together
- or an even better solution could be to have just one tile in the legend which is double colored. Something like this:
Could you please help me solving this issue?
Many thanks in advance!
Yes, you can do that. Note however that you can't really modify the original
Legend
. So for a perfect result you would need to create a new customLegend
instead.See here for an example that does that; note especially the positioning..!
But maybe you can get away a little easier; see below!
The first rule to understand is that added
LegendItems
always go to the end of the list. So you can't keep them together, unless your addedSeries
are at the start. You can do that by usingSeries.Insert(..)
but using those two-color rectangles is much nicer, imo..To show the graphics you want, simply create them as bitmaps, either on disk or on the fly and store them in the
Images
collection of the chart:Now add it to the chart's
NamedImage
collection:Now you can create as many
LegendItems
as you need:And add them to the
Legend
:Unfortunately you can't delete the original item.
What you can do, besides creating a new
Legend
from scratch, is this:Clear the text like this:
As you have set the
Colors
of all theDataPoints
anyway, you can also get rid of the blue rectangle:This will also make all points without colors transparent, so make sure to color them all!
Note that some space in the Legend it still taken!
Here is the result, with a few colored points and your line series added: