我正在控制台应用程序中工作,并尝试在 C# 控制台中绘制图表,但我无法将标记与 X 轴上的值对齐,我尝试向星号添加间距,但什么也没有,有什么想法吗?我应该用循环来做到这一点
理想情况下,我想在 X 轴上的值的第二位数字上方打印标记
这是存储在数组 pHValues[] 和dates[] 中的数据作为参考
Date, pH Level
10-21-2023, 12.3
10-22-2023, 11.9
10-23-2023, 13.6
10-24-2023, 11.9
10-25-2023, 10.8
这是我的代码:
static void DisplayChart(double[] pHValues, string[] dates, int count)
{
string message = "\nNo entries available for the graph. ";
if (count == 0)
{
DisplayContinueMessage(message);
return;
}
var distinctPhValues = pHValues.Distinct().OrderByDescending(x => x).ToArray();
foreach (var value in distinctPhValues)
{
//print pH values in the Y-axis
Console.Write($"{value:0.0}| ");
for (int i = 0; i < count; i++)
{
if (pHValues[i] == value)
{
Console.Write(" * ");
}
else
{
Console.Write(" ");
}
}
Console.WriteLine();
}
// Print dates on the X-axis
Console.WriteLine("----------------------");
Console.Write("Day| ");
for (int i = 0; i < count; i++)
{
Console.Write($"{dates[i].Substring(3, 2)} ");
}
Console.ReadLine();
}
这就是我得到的:
13.6| *
12.3| *
11.9| * *
10.8| *
0.0|
----------------------
Day| 21 22 23 24 25
X 轴日期的第二位数字彼此间隔 3 个字符。对齐 Y 轴后,您所需要做的就是重复打印一个空格/星号,然后再打印 3 个空格。
要对齐 Y 轴,您只需找到包含最多字符的 ph 值即可找到其宽度(当然,如果您知道这些值必须在某个范围内,还有更快的方法):
var yAxisWidth = distinctPhValues
.Select(x => $"{x:0.0}".Length).Max();
然后,您可以使用
PadLeft
(如果您想要左对齐,则使用 PadRight
)来打印 ph 值。
foreach (var value in distinctPhValues)
{
//print pH values in the Y-axis
Console.Write($"{value:0.0}".PadLeft(yAxisWidth));
Console.Write("| "); // note I added an extra space here to account for the first digit of the dates
for (int i = 0; i < pHValues.Length; i++)
{
if (pHValues[i] == value)
{
Console.Write("*");
}
else
{
Console.Write(" ");
}
Console.Write(" "); // the stars are all 3 spaces apart from each other
}
Console.WriteLine();
}
x 轴的长度很容易计算 - 将
dates.Length
乘以每个日期占用的字符数(即 4),然后加上 Y 轴的宽度
Console.WriteLine(new string('-', yAxisWidth + 4 * dates.Length));
Console.Write("Day".PadLeft(yAxisWidth));
Console.Write("| ");
for (int i = 0; i < dates.Length; i++)
{
// consider actually using a DateTime/DateOnly instead of strings to represent dates
Console.Write($"{dates[i].Substring(3, 2)} ");
}
用法示例:
DisplayChart(
new double[] {
12.3, 11.9, 13.6, 11.9, 10.8
},
new string[] {
"10-21-2023",
"10-22-2023",
"10-23-2023",
"10-24-2023",
"10-25-2023",
}
);
输出示例:
13.6| *
12.3| *
11.9| * *
10.8| *
------------------------
Day| 21 22 23 24 25