在C#.net的饼图中设置颜色
作者:互联网
我试图使用从C#.NET数据库中提取的数据创建一个简单的饼图.我使用了以下代码-
string[] xAxis = { "Banana", "Mango", "Apple" };
double BananaPercentage= 40;
double MangoPercentage= 30;
double ApplePercentage = 30;
double[] Percentage = { BananaPercentage, MangoPercentage, ApplePercentage };
Color[] PieColors = { Color.Green, Color.Red, Color.Gray };
chart1.Series[0].Label = "#PERCENT";
chart1.Series[0].LegendText = "#AXISLABEL";
//chart1.Series[0].Points[0].Color = PieColors[0];
chart1.Series[0].Points.DataBindXY(xAxis, Percentage);
它显示具有正确值的饼图.但是,当我尝试为香蕉(绿色),芒果(红色)和苹果(灰色)分配特定颜色时,它显示错误“索引超出范围.必须为非负数….”.
谁能给我任何提示,这是怎么了?
解决方法:
“索引超出范围…”是因为chart1.Series [0] .Points [0],尤其是.Points [0].不是因为PieColors [0].如果要进一步使用它们或要更改其颜色,则应在前面添加一些点.例如 :
int index = chart1.Series[0].Points.AddXY(x, y);
然后您可以执行以下操作:
chatr1.Series[0].Points[index].Color = PieColors[0]; //or whatever color
在您的情况下,问题是,您尝试分配Point的颜色后将点绑定到chart1.Series [0] .Points.尝试更改此:
chart1.Series[0].Label = "#PERCENT";
chart1.Series[0].LegendText = "#AXISLABEL";
chart1.Series[0].Points[0].Color = PieColors[0];
chart1.Series[0].Points.DataBindXY(xAxis, Percentage);
至
chart1.Series[0].Label = "#PERCENT";
chart1.Series[0].LegendText = "#AXISLABEL";
chart1.Series[0].Points.DataBindXY(xAxis, Percentage);
chart1.Series[0].Points[0].Color = PieColors[0];
chart1.Series[0].Points[1].Color = PieColors[1];
chart1.Series[0].Points[2].Color = PieColors[2];
如果要更改“系列”颜色而不是“点”,则可以编写如下内容:
chart1.Series[0].Color = Color.Red; //or any other color, maybe from PieColor
标签:pie-chart,c 来源: https://codeday.me/bug/20191121/2050416.html