添加标题到我的系列行[mschart]

时间:2014-03-12 11:00:35

标签: c# charts mschart

我正在使用Chart control来显示我的网络统计信息(下载,上传):

chart1.Titles.Add("Test Chart");

Series seriesDownload = new Series("KB/s");
seriesDownload.Color = Color.DarkBlue;
seriesDownload.ChartType = SeriesChartType.Spline;
seriesDownload.BorderWidth = 2;
chart1.Series.Add(seriesDownload);

Series seriesPps = new Series("pps");
seriesPps.Color = Color.Black;
seriesPps.ChartType = SeriesChartType.Spline;
seriesPps.BorderWidth = 2;
chart1.Series.Add(seriesPps);

是否可以在每行附近添加文字以区分两种颜色?

enter image description here

private void chartTimer_Tick(object sender, EventArgs e)
{
    chart1.Series[1].LegendText = chart1.Series[1].Name = str + " KB/s";
    DataPoint Point = chart1.Series[1].Points[chart1.Series[1].Points.Count - 1];
    Point.Label = chart1.Series[1].Name;

    DataPoint _point = default(DataPoint);
    foreach (DataPoint item in chart1.Series[1].Points)
    {
       item.Label = "";
       item.MarkerStyle = MarkerStyle.None;
    }
}

2 个答案:

答案 0 :(得分:1)

这样的内容会在系列的最后一个点添加一个带有系列名称的标签。这是VB.NET,但您应该能够将其解析为C#

'remove all previous datapoint labels
Dim _point As DataPoint
For Each _point In Chart1.Series(i).Points
    _point.Label = ""
    _point.MarkerStyle = MarkerStyle.None
Next


'add label to last point
Dim Point As DataPoint = Chart1.Series(i).Points(Chart1.Series(i).Points.Count - 1)
Point.Label = Chart1.Series(i).Name
Point.MarkerStyle = MarkerStyle.Circle

enter image description here

或者您是否希望用系列名称填充图例?然后

Chart1.Series(i).LegendText = Chart1.Series(i).Name

编辑 根据C# 中的askee提交的代码

private void chartTimer_Tick(object sender, EventArgs e)
{

    foreach (DataPoint item in chart1.Series[1].Points)
    {
        item.Label = "";
    }

    chart1.Series[1].LegendText = chart1.Series[1].Name = str + " KB/s";
    DataPoint Point = chart1.Series[1].Points[chart1.Series[1].Points.Count - 1];
    Point.Label = chart1.Series[1].Name;

}

答案 1 :(得分:0)

更改系列名称并不是一种好习惯,因为SeriesCollection可以按名称编制索引(例如chart1.Series["MySeries"]),这可能会在名称更改后失败。

如果您尝试在代码末尾添加静态标签,则可以将其作为智能标签。查看要在标签中使用的"#VALX#", "#VAL#"修饰符:

DataPoint Point = chart1.Series[1].Points[chart1.Series[1].Points.Count - 1];
Point.Label = "#VAL" + " kB/s";

会自动将当前的x或y值添加到标签中。见http://msdn.microsoft.com/en-us/library/dd456687(v=vs.110).aspx

顺便说一句,将Series的名称放入类中的const变量(或另一个类中的静态变量)非常有用,因此您可以将它们编入索引,而不必担心打字错误。使您的代码更容易理解。

private const string _downloadSeries = "download";

// in some initialization method
Series seriesDownload = new Series(_downloadSeries);
chart1.Series.Add(seriesDownload);

// Access the series
DataPoint point = chart1.Series[_downloadSeries].Points[0];

例如。

编辑:如果你只是想区分这两种颜色,那就是传说的真正含义。如果您还想显示最新值,那么此代码将执行此操作