以编程方式创建图表并设置其图例

问题描述 投票:-2回答:1

我正在创建图表饼图,条形图和折线图,并希望将其图例以及valuea,图例标题设置为图表。我该怎么办?

c# winforms-interop
1个回答
0
投票

通常,您不需要添加Legend,因为已经有一个默认值。但是,由于要在代码中创建Chart,因此确实需要多编写一些代码。添加Legend是这些事情的[[one。

您已经创建了一个legend,但是没有添加它,而是仍然创建了另一个图例。改写:chartA.Legends.Add(legend)

请注意,带有字符串参数的constructor上的文档(包括Intellisense)是错误的!它可以按预期运行,而不像MSDN上记录的那样!

如果您已完成所需的所有其他操作,我的建议(chartA.Legends[0].Title = "someString";)效果很好:

您还必须创建(至少)

    一个ChartArea
  • 一个Series和您想要的一个ChartType。>
  • ..为了使其显示出来,您还必须添加DataPoint
  • 示例:

Legend legend = new Legend(); Chart chartA = new Chart(); // <<---! chartA.BackColor = Color.White; chartA.Width = 370; chartA.Height = 250; chartA.Location = new Point(48, 35); chartA.Name = textBox1.Text; chartA.Legends.Add(legend); // <<---! legend.Title = "Age of The Employees"; // <<---! chartA.ChartAreas.Add(new ChartArea("ca")); // <<---! chartA.ChartAreas["ca"].BackColor = Color.LightSeaGreen; Series s1 = chartA.Series.Add("s1"); // <<---! s1.ChartType = SeriesChartType.Pie; s1.Points.AddY(12); s1.Points.AddY(32); ..

第一个Legend

自动

或者每个LegendItem填充一个Series (如果您有Pie图表)填充一个DataPoint
顺便说一句:您可能还有其他Legends,但您必须注意它们的内容及其位置/停放处。

更新:如果需要,您可以同时控制图例的FontTitleFont;它以通常的方式工作,即从FontFontFamily的头创建新的Font

legend.Font = new Font("Consolas", 10f); legend.TitleFont = new Font(legend.Font.FontFamily, 14f);

如果标题太长而无法容纳在垂直图例中,则可能需要在标题中插入换行符(\n)。>
© www.soinside.com 2019 - 2024. All rights reserved.