namespace Spectre.Console;
///
/// A renderable (horizontal) bar chart.
///
public sealed class BarChart : Renderable, IHasCulture
{
///
/// Gets the bar chart data.
///
public List Data { get; }
///
/// Gets or sets the width of the bar chart.
///
public int? Width { get; set; }
///
/// Gets or sets the bar chart label.
///
public string? Label { get; set; }
///
/// Gets or sets the bar chart label alignment.
///
public Justify? LabelAlignment { get; set; } = Justify.Center;
///
/// Gets or sets a value indicating whether or not
/// values should be shown next to each bar.
///
public bool ShowValues { get; set; } = true;
///
/// Gets or sets the culture that's used to format values.
///
/// Defaults to invariant culture.
public CultureInfo? Culture { get; set; }
///
/// Gets or sets the fixed max value for a bar chart.
///
/// Defaults to null, which corresponds to largest value in chart.
public double? MaxValue { get; set; }
///
/// Gets or sets the function used to format the values of the bar chart.
///
public Func? ValueFormatter { get; set; }
///
/// Initializes a new instance of the class.
///
public BarChart()
{
Data = new List();
}
///
protected override Measurement Measure(RenderOptions options, int maxWidth)
{
var width = Math.Min(Width ?? maxWidth, maxWidth);
return new Measurement(width, width);
}
///
protected override IEnumerable Render(RenderOptions options, int maxWidth)
{
var width = Math.Min(Width ?? maxWidth, maxWidth);
var maxValue = Math.Max(MaxValue ?? 0d, Data.Max(item => item.Value));
var grid = new Grid();
grid.Collapse();
grid.AddColumn(new GridColumn().PadRight(2).RightAligned());
grid.AddColumn(new GridColumn().PadLeft(0));
grid.Width = width;
if (!string.IsNullOrWhiteSpace(Label))
{
grid.AddRow(Text.Empty, new Markup(Label).Justify(LabelAlignment));
}
foreach (var item in Data)
{
grid.AddRow(
new Markup(item.Label),
new ProgressBar()
{
Value = item.Value,
MaxValue = maxValue,
ShowRemaining = false,
CompletedStyle = new Style().Foreground(item.Color ?? Color.Default),
FinishedStyle = new Style().Foreground(item.Color ?? Color.Default),
UnicodeBar = '█',
AsciiBar = '█',
ShowValue = ShowValues,
Culture = Culture,
ValueFormatter = ValueFormatter,
});
}
return ((IRenderable)grid).Render(options, width);
}
}