Горизонтальная гистограмма
Горизонтальная диаграмма будет проще всего для этого, когда мы отображаем значения по горизонтали и ключи (слова) по вертикали, потому что у нас есть «неограниченное» вертикальное пространство и там вероятно, будет много слов для отображения данных.
Также проще создать такой график, поскольку мы записываем все данные для одного слова в одну строку. Мы могли бы сделать вертикальную диаграмму, но это было бы немного хитрее.
Я бы сделал что-то вроде этого:
- Во всех oop, для Для каждого элемента напишите слово и добавьте слева от него пробелы, чтобы у нас было четное левое поле для графа
- Напишите строку из
█
символов, представляющих количество экземпляров слова
Например:
// Populate some random word counts for an example
var RepeatedWordCount = new Dictionary<string, int>
{
{"the", 20}, {"you", 13}, {"was", 9}, {"as", 5},
{"a", 17}, {"in", 15}, {"I", 1}, {"he", 10},
{"they", 2}, {"of", 19}, {"on", 7}, {"that", 12},
{"his", 3}, {"it", 11}, {"to", 16}, {"for", 8},
{"are", 6}, {"with", 4}, {"is", 14}, {"and", 18},
};
// Get the length of the longest word so we can pad all
// words to the same length and have an even margin
var maxWordLength = RepeatedWordCount.Keys.Max(k => k.Length);
// Create some colors to differentiate the bars
var colors = new[]
{
ConsoleColor.Red, ConsoleColor.DarkBlue, ConsoleColor.Green,
ConsoleColor.DarkYellow, ConsoleColor.Cyan, ConsoleColor.DarkMagenta,
ConsoleColor.DarkRed, ConsoleColor.Blue, ConsoleColor.DarkGreen,
ConsoleColor.Yellow, ConsoleColor.DarkCyan, ConsoleColor.Magenta,
};
var colorIndex = 0;
foreach (KeyValuePair<string, int> kvp in RepeatedWordCount)
{
// Write the word and vertical line
Console.Write(kvp.Key.PadLeft(maxWordLength + 2, ' ') + " | ");
// Write the chart value using the next color in the array
Console.ForegroundColor = colors[colorIndex++ % colors.Length];
Console.WriteLine(new string('█', kvp.Value));
Console.ResetColor();
}
Console.Write("\nDone! Press any key to exit...");
Console.ReadKey();
Пример вывода
![enter image description here](https://i.stack.imgur.com/dkqvF.png)
Вертикальная гистограмма
Теперь, когда мы видим, как сделать горизонтальный график, мы можем подумать о том, как сделать вертикальный график. В этом случае нам нужно знать значения для каждой строки, а затем, начиная с верхней части диаграммы, где «строка» является максимальным значением, записать блок solid для каждой строки, значение которой равно или больше значения текущей строки.
В нижней части диаграммы нам нужно написать каждое слово вертикально, поэтому нам нужно написать по одному символу на строку для каждого.
Возможно, какой-то код более нагляден:
// Populate some random word counts for an example
var RepeatedWordCount = new Dictionary<string, int>
{
{"the", 20}, {"you", 13}, {"was", 9}, {"as", 5},
{"a", 17}, {"in", 15}, {"I", 1}, { "he", 10},
{"they", 2}, {"of", 19}, {"on", 7}, {"that", 12},
{"his", 3}, {"it", 11}, {"to", 16}, {"for", 8},
{"are", 6}, {"with", 4}, {"is", 14}, {"and", 18},
};
// Get the count value for the word with the highest count
var maxWordCount = RepeatedWordCount.Values.Max();
// Create some colors to differentiate the bars
var colors = new[]
{
ConsoleColor.Red, ConsoleColor.DarkBlue, ConsoleColor.Green,
ConsoleColor.DarkYellow, ConsoleColor.Cyan, ConsoleColor.DarkMagenta,
ConsoleColor.DarkRed, ConsoleColor.Blue, ConsoleColor.DarkGreen,
ConsoleColor.Yellow, ConsoleColor.DarkCyan, ConsoleColor.Magenta,
};
Console.WriteLine();
// Get all the counts
var values = RepeatedWordCount.Values.ToList();
// Start at the top of the chart, where the value is maxWordCount
// and work our way down, writing a block for each string that
// has a value greater than or equal to the count for that row
for (int i = maxWordCount; i > 0; i--)
{
for (int j = 0; j < RepeatedWordCount.Count; j++)
{
Console.ForegroundColor = colors[j % colors.Length];
Console.Write(values[j] >= i ? "███" : " ");
Console.ResetColor();
}
Console.WriteLine();
}
// Write each word vertically below it's line
var words = RepeatedWordCount.Keys.ToList();
var maxWordLength = words.Max(w => w.Length);
for (var i = 0; i < maxWordLength; i++)
{
foreach (var word in words)
{
Console.Write(word.Length > i ? $" {word[i]} " : " ");
}
Console.WriteLine();
}
Console.Write("\nDone! Press any key to exit...");
Console.ReadKey();
Пример вывода
![enter image description here](https://i.stack.imgur.com/i1pR3.png)