c# - 使图表图例代表两种颜色

标签 c# .net winforms charts legend

我在应用程序中创建了一个柱形图,如下所示:

Column chart with positive and negative colors

如您所见,正值是绿色,负值是红色。我需要在图例中体现这一点。我只是不知道怎么办。

我已经尝试过的:

我将 CustomItems 添加到 Legend 中。这是代码:

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);
}

这会产生以下表示:

Column chart with legend representing positive and negative color

我可以忍受这一点。但是,一旦我向图表中添加更多系列,元素的顺序就会被破坏。这是一个例子:

enter image description here

我想要以下两个选项之一:

  1. 将正色和负色放在一起
  2. 或者更好的解决方案可能是图例中只有一个双色图 block 。像这样的事情:

enter image description here

您能帮我解决这个问题吗?

非常感谢!

最佳答案

是的,你可以做到。但请注意,您无法真正修改原始 Legend 。因此,为了获得完美的结果,您需要创建一个新的自定义 Legend相反。

参见here for an example就是这样做的;特别注意定位..!

但也许你可以轻松一点;见下文!

要理解的第一条规则是添加 LegendItems总是转到列表的末尾。所以你不能把它们放在一起,除非你添加 Series位于开始处。您可以使用 Series.Insert(..) 来做到这一点但在我看来,使用那些两种颜色的矩形要好得多..

要显示您想要的图形,只需将它们创建为位图(在磁盘上或动态创建)并将它们存储在 Images 中。图表集合:

Legend L = chart1.Legends[0];
Series S = chart1.Series[0];

// either load an image from disk (or resources)
Image img = Image.FromFile(someImage);

// or create it on the fly:
Bitmap bmp = new Bitmap(32, 14);
using (Graphics G = Graphics.FromImage(bmp))
{
    G.Clear(Color.Red);
    G.FillPolygon(Brushes.LimeGreen, new Point[] { new Point(0,0), 
        new Point(32,0), new Point(0,14)});
}

现在将其添加到图表的 NamedImage 中收藏:

chart1.Images.Add(new NamedImage("dia", bmp));

现在您可以创建任意数量的LegendItems根据您的需要:

LegendItem newItem = new LegendItem();
newItem.ImageStyle = LegendImageStyle.Rectangle;
newItem.Cells.Add(LegendCellType.Image, "dia", ContentAlignment.MiddleLeft);
newItem.Cells.Add(LegendCellType.Text, S.Name, ContentAlignment.MiddleLeft);

并将它们添加到 Legend :

L.CustomItems.Add(newItem);

遗憾的是,您无法删除原始项目。

除了创建新的Legend之外,您还可以做什么从头开始,是这样的:

像这样清除文本:

S.LegendText = " "; // blank, not empty!

正如您设置的 Colors 所有 DataPoints不管怎样,你也可以去掉蓝色矩形:

S.Color = Color.Transparent;

这也会使所有没有颜色的点变得透明,所以一定要给它们全部着色!

请注意,它仍然占用了图例中的一些空间!

这是结果,添加了一些彩色点和线系列:

enter image description here

关于c# - 使图表图例代表两种颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36614148/

相关文章:

c# - 使用c#提取excel中嵌入的 ‘pdf’文件并将其保存到文件夹中

c# - ICSharpCode.TextEditor 垂直滚动

c# - 哪个更好 : dictionary or hashtable

winforms - 哪些文件需要用cefsharp winforms应用程序打包

.NET:如何检查鼠标是否在控件中?

c# - 背景 worker 。如何通过在 TreeView 中导航来显示当前进程?

c# - .net web api 服务器中的静态变量

c# - 是否有一个 IEnumerable 实现只迭代一次它的源代码(例如 LINQ)?

c# - ServiceStack:解析未知类型的服务

c# - WebBrowser 文本选择更改时触发事件