LiveCharts文檔-3開始-7標簽
Label就是Chart中表示數值的字符串,通常被放置在軸的位置和提示當中。
下圖中的這些字符串顯示的都是標簽
using System;
using System.Windows.Forms;
using LiveCharts;
using LiveCharts.Defaults;
using LiveCharts.Wpf;
namespace Winforms.Cartesian.Labels
{
public partial class Labels : Form
{
public Labels()
{
InitializeComponent();
}
private void Labels_Load(object sender, EventArgs e)
{
cartesianChart1.Series.Add(new ColumnSeries
{
Values = new ChartValues<ObservableValue>
{
new ObservableValue(4),
new ObservableValue(2),
new ObservableValue(8),
new ObservableValue(2),
new ObservableValue(3),
new ObservableValue(0),
new ObservableValue(1),
},
DataLabels = true,
LabelPoint = point => point.Y + "K"
});
cartesianChart1.AxisX.Add(new Axis
{
Labels = new[]
{
"Shea Ferriera",
"Maurita Powel",
"Scottie Brogdon",
"Teresa Kerman",
"Nell Venuti",
"Anibal Brothers",
"Anderson Dillman"
},
Separator = new Separator // force the separator step to 1, so it always display all labels
{
Step = 1,
IsEnabled = false //disable it to make it invisible.
},
LabelsRotation = 15
});
cartesianChart1.AxisY.Add(new Axis
{
LabelFormatter = value => value + ".00K items",
Separator = new Separator()
});
}
}
}
LiveCharts有兩種類型的Label,格式化類型和映射類型。
格式化類型
當Chart當中的值和label之間存在直接轉換的時候,格式化類型的Label會很有用。比如,在下面的圖片中,Y軸值的范圍從8到26,但是因為現在的格式化器的作用,我們能夠看到8被顯示為8.00k。
Axis.LabelFormatter 可以使用double類型的值作為輸入,返回一個string,LiveCharts每次在需要將表的值顯示為字符串的時候,就會使用這個函數。
MyAxis.LabelFormatter = val => val.ToString("C"); //as currency
MyAxis.LabelFormatter = val => val + "°"; //as degrees
MyAxis.LabelFormatter = val => val + ".00 items sold"; //or any other custom format
映射類型
當需要用一個名稱映射位置的時候,映射類型會很有用,比如第一個點屬於john,第二個屬於susan,第三個屬於charles。
cartesianChart1.AxisX.Add(new LiveCharts.Wpf.Axis
{
Labels = new[]
{
"Shea Ferriera",
"Maurita Powel",
"Scottie Brogdon",
"Teresa Kerman",
"Nell Venuti",
"Anibal Brothers",
"Anderson Dillman"
}
});
映射類型意味着,軸的值將會用Axis.Labels屬性當中的字符串來表示,Axis.Labels類型是IList
請注意到軸的值大於Labels的總數的時候,會返回空字符串。
Axis.Labels隱藏了一個Axis.LabelFormatte,因此當Axis.Labels不是null,那么標簽將會從Axis.Labels中找,如果Axis.Labels是null,那么Livecharts將會使用格式化器,如果都是null,那么原始值會被返回。
數據標簽
當你需要你的series上的每個點都有一個標簽的時候,設置Series.DataLabels屬性為true即可。如果必要的話,可以自定義數據標簽,使用Series.LabelPoint 屬性
new ColumnSeries
{
Values = new ChartValues>double> { 4, 2, 8, 2, 3, 0, 1 },
DataLabels = true,
LabelPoint = point => point.Y + "K"
}
旋轉標簽
有時候你的標簽長度過長,你就需要權衡一下位置,這時候你就可以旋轉標簽,可以使用任何角度,甚至是負的角度(反方向旋轉)。
cartesianChart1.AxisX.Add(new LiveCharts.Wpf.Axis
{
Labels = new[]
{
"Shea Ferriera",
"Maurita Powel",
"Scottie Brogdon",
"Teresa Kerman",
"Nell Venuti",
"Anibal Brothers",
"Anderson Dillman"
},
LabelsRotation = 13,
Separator = new Separator // force the separator step to 1, so it always display all labels
{
Step = 1, // if you don't force the separator, it will be calculated automatically, and could skip some labels
IsEnabled = false //disable it to make it invisible.
}
});