UltraChart の凡例ラベルの文字色を系列ごとに変更するには、ChartDrawItem イベントを使用します。イベント引数の Primitive を Text 型にキャストし、labelStyle.FontColor プロパティに色を設定します。

UltraChart の設定

凡例を表示するには Legend.Visible を true に設定します。また、各系列の凡例ラベルとして表示される文字列を XYSeries.Label で指定し、系列の描画色は PEs コレクションに PaintElement を追加して設定します。

ultraChart1.ChartType = ChartType.ScatterChart;
ultraChart1.Legend.Visible = true;
ultraChart1.Legend.SpanPercentage = 25;
ultraChart1.Legend.Font = new Font(ultraChart1.Legend.Font.FontFamily, 12);

for (var i = 1; i < 4; i++)
{
    var series = new XYSeries();
    series.Data.DataSource = table;
    series.Data.ValueXColumn = "X" + i;
    series.Data.ValueYColumn = "Y" + i;
    series.Label = "MySeries " + i;
    series.Key   = "MySeries " + i;
    series.DataBind();
    ultraChart1.Series.Add(series);
}

ultraChart1.Series[0].PEs.Add(new PaintElement(Color.Red));
ultraChart1.Series[1].PEs.Add(new PaintElement(Color.Blue));
ultraChart1.Series[2].PEs.Add(new PaintElement(Color.Green));

ここまでの設定で、凡例が表示されます。

ChartDrawItem イベントの処理

ChartDrawItem イベントは、チャートの各描画プリミティブが描画される直前に発生します。イベント引数 e.Primitive を Text 型にキャストし、GetTextString() で凡例ラベルの文字列を取得します。対象の系列名と一致した場合に labelStyle.FontColor プロパティへ色を設定することで、凡例ラベルの文字色を変更できます。

private void ultraChart1_ChartDrawItem(object sender, ChartDrawItemEventArgs e)
{
    if (e.Primitive is Text txt)
    {
        switch (txt.GetTextString())
        {
            case "MySeries 1":
                txt.labelStyle.FontColor = Color.Red;
                break;
            case "MySeries 2":
                txt.labelStyle.FontColor = Color.Blue;
                break;
            case "MySeries 3":
                txt.labelStyle.FontColor = Color.Green;
                break;
        }
    }
}

実行結果

各系列の凡例ラベルが、対応する系列の描画色(赤・青・緑)と同じ色で表示されます。

Tagged:

製品について

Ultimate UI for Windows Forms