.NET图表控件:在添加和删除其他系列时保留系列颜色?

3

在向.net图表控件(折线图)添加和删除系列时,如何保留现有系列的颜色?

当前,当我向图表添加几个系列时,它们都会自动从图表调色板中分配颜色。但是如果我删除第一个系列,则所有后续系列的颜色将根据图表调色板中的顺序重置。是否有任何方法可以阻止这种情况发生?

提前致谢。

3个回答

5
为什么不直接设置图表颜色而不使用调色板?
Chart.Palette = ChartColorPalette.None;
Chart.Series[0].Color = Color.Green;

等等,这意味着您必须在添加每个系列时设置颜色,但是这就是生活。


0

首先,您需要调用ApplyPaletteColors来打破自动着色方案。

然后,您可以为每个系列应用其自己的调色板颜色,并使其保持不变:

chart1.ApplyPaletteColors();
series1.Color = series1.Color;
series2.Color = series2.Color;
// or, of course..:    
series1.Color = someColor;
series2.Color = someOtherColor;
..

0

我发现,如果在设置图表时添加所有系列,并根据需要启用或禁用它们,它将保留分配给系列的相同颜色。

我想你遇到的问题实际上是从图表中删除系列,然后将其作为新系列添加回去(我认为这会导致它采用调色板中的下一个颜色)。

在我现在正在处理的图表中,我实际上添加了复选框来控制是否启用或禁用系列,并且它一直保持所有系列的相同颜色。

// Assuming I have chart set up with chart area and 3 series.
chart.Series.Add(s1);
chart.Series.Add(s2);
chart.Series.Add(s3);

CheckBox cb1 = new CheckBox();
cb1.Text = s1.Name;
cb.Checked = s1.Enabled;
// Set up action for when checkbox is changed.
cb.CheckedChanged += delegate (object sender, EventArgs e)
{  
  // Set series enabled property based on check box Checked property
  s1.Enabled = cb.Checked;
  // Will recalculate the scale to show the remaining series better.
  // If you do not want to adjust chart size for remaining series,
  // this can be removed.
  chart.ChartAreas[s1.ChartArea].RecalculateAxesScale();
  // Force redraw of chart area
  chart.Invalidate();
};
this.Controls.Add(cb1);

// Repeat for additional check boxes and add to UI 

希望这能帮助到后来遇到这个问题的人。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接