├── .gitattributes ├── .github ├── release.yml └── workflows │ └── build-and-release.yml ├── .gitignore ├── LICENSE.txt ├── README.md ├── docs ├── API.md └── nuget_readme.md ├── images ├── icon_128x128.png ├── icon_32x32.png ├── nuget_quickstart_console.png └── quickstart_console.png └── src ├── ConsolePlot.Examples ├── ConsolePlot.Examples.csproj └── Program.cs ├── ConsolePlot.sln └── ConsolePlot ├── ConsolePlot.csproj ├── Drawing ├── AbstractGraphics.cs ├── ConsoleGraphics.cs ├── ConsoleImage.cs ├── Pixel.cs ├── Rectangle.cs ├── TextDirection.cs ├── Tools │ ├── BrailleBrush.cs │ ├── ConsolePointBrush.cs │ ├── ConsolePointPen.cs │ ├── IPointBrush.cs │ ├── LineBrush.cs │ ├── LinePen.cs │ ├── PointPen.cs │ ├── QuadrantBrush.cs │ ├── SystemLineBrushes.cs │ └── SystemPointBrushes.cs └── VirtualGraphics.cs ├── Plot.cs └── Plotting ├── AxisSettings.cs ├── Bounds.cs ├── CoordinateConverter.cs ├── GraphGraphics.cs ├── GridSettings.cs ├── LabelSettings.cs ├── PlotData.cs ├── PlotRenderer.cs ├── PlotSettings.cs ├── Point.cs ├── Series.cs ├── Tick.cs └── TickSettings.cs /.gitattributes: -------------------------------------------------------------------------------- 1 | ############################################################################### 2 | # Set default behavior to automatically normalize line endings. 3 | ############################################################################### 4 | * text=auto 5 | 6 | ############################################################################### 7 | # Set default behavior for command prompt diff. 8 | # 9 | # This is need for earlier builds of msysgit that does not have it on by 10 | # default for csharp files. 11 | # Note: This is only used by command line 12 | ############################################################################### 13 | #*.cs diff=csharp 14 | 15 | ############################################################################### 16 | # Set the merge driver for project and solution files 17 | # 18 | # Merging from the command prompt will add diff markers to the files if there 19 | # are conflicts (Merging from VS is not affected by the settings below, in VS 20 | # the diff markers are never inserted). Diff markers may cause the following 21 | # file extensions to fail to load in VS. An alternative would be to treat 22 | # these files as binary and thus will always conflict and require user 23 | # intervention with every merge. To do so, just uncomment the entries below 24 | ############################################################################### 25 | #*.sln merge=binary 26 | #*.csproj merge=binary 27 | #*.vbproj merge=binary 28 | #*.vcxproj merge=binary 29 | #*.vcproj merge=binary 30 | #*.dbproj merge=binary 31 | #*.fsproj merge=binary 32 | #*.lsproj merge=binary 33 | #*.wixproj merge=binary 34 | #*.modelproj merge=binary 35 | #*.sqlproj merge=binary 36 | #*.wwaproj merge=binary 37 | 38 | ############################################################################### 39 | # behavior for image files 40 | # 41 | # image files are treated as binary by default. 42 | ############################################################################### 43 | #*.jpg binary 44 | #*.png binary 45 | #*.gif binary 46 | 47 | ############################################################################### 48 | # diff behavior for common document formats 49 | # 50 | # Convert binary document formats to text before diffing them. This feature 51 | # is only available from the command line. Turn it on by uncommenting the 52 | # entries below. 53 | ############################################################################### 54 | #*.doc diff=astextplain 55 | #*.DOC diff=astextplain 56 | #*.docx diff=astextplain 57 | #*.DOCX diff=astextplain 58 | #*.dot diff=astextplain 59 | #*.DOT diff=astextplain 60 | #*.pdf diff=astextplain 61 | #*.PDF diff=astextplain 62 | #*.rtf diff=astextplain 63 | #*.RTF diff=astextplain 64 | -------------------------------------------------------------------------------- /.github/release.yml: -------------------------------------------------------------------------------- 1 | changelog: 2 | categories: 3 | - title: Breaking Changes 4 | labels: 5 | - breaking-change 6 | - title: New Features 7 | labels: 8 | - enhancement 9 | - title: Bug Fixes 10 | labels: 11 | - bug 12 | - title: Other Changes 13 | labels: 14 | - "*" -------------------------------------------------------------------------------- /.github/workflows/build-and-release.yml: -------------------------------------------------------------------------------- 1 | name: Build and Upload Release 2 | 3 | on: 4 | push: 5 | tags: 6 | - "v[0-9]+.[0-9]+.[0-9]+" 7 | - "v[0-9]+.[0-9]+.[0-9]+-*" 8 | 9 | jobs: 10 | build_and_release: 11 | runs-on: ubuntu-latest 12 | 13 | steps: 14 | - name: Checkout code 15 | uses: actions/checkout@v4 16 | with: 17 | fetch-depth: 0 18 | 19 | - name: Setup .NET 20 | uses: actions/setup-dotnet@v4 21 | with: 22 | dotnet-version: '8.0.x' 23 | 24 | - name: Get version from tag 25 | id: get_version 26 | run: echo "VERSION=${GITHUB_REF#refs/tags/v}" >> $GITHUB_OUTPUT 27 | 28 | - name: Get numeric version 29 | id: get_numeric_version 30 | run: echo "NUMERIC_VERSION=$(echo ${{ steps.get_version.outputs.VERSION }} | sed 's/-.*//')" >> $GITHUB_OUTPUT 31 | 32 | - name: Generate changelog link 33 | id: generate_changelog_link 34 | run: echo "CHANGELOG_URL=https://github.com/${{ github.repository }}/releases/tag/v${{ steps.get_version.outputs.VERSION }}" >> $GITHUB_OUTPUT 35 | 36 | - name: Build and Create NuGet Package 37 | run: > 38 | dotnet pack ./src/ConsolePlot/ConsolePlot.csproj 39 | -p:PackageVersion=${{ steps.get_version.outputs.VERSION }} 40 | -p:AssemblyVersion=${{ steps.get_numeric_version.outputs.NUMERIC_VERSION }} 41 | -p:FileVersion=${{ steps.get_numeric_version.outputs.NUMERIC_VERSION }} 42 | -p:PackageReleaseNotes="${{ steps.generate_changelog_link.outputs.CHANGELOG_URL }}" 43 | -p:IncludeSymbols=true 44 | -p:SymbolPackageFormat=snupkg 45 | --configuration Release 46 | --output . 47 | 48 | - name: Push to NuGet 49 | run: dotnet nuget push *.nupkg --source https://api.nuget.org/v3/index.json --api-key ${{secrets.NUGET_API_KEY}} --skip-duplicate 50 | 51 | - name: Create GitHub Release 52 | uses: softprops/action-gh-release@v2 53 | with: 54 | name: ${{ steps.get_version.outputs.VERSION }} 55 | draft: false 56 | prerelease: ${{ contains(github.ref, '-') }} 57 | generate_release_notes: true -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | ## Ignore Visual Studio temporary files, build results, and 2 | ## files generated by popular Visual Studio add-ons. 3 | ## 4 | ## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore 5 | 6 | # User-specific files 7 | *.rsuser 8 | *.suo 9 | *.user 10 | *.userosscache 11 | *.sln.docstates 12 | 13 | # User-specific files (MonoDevelop/Xamarin Studio) 14 | *.userprefs 15 | 16 | # Mono auto generated files 17 | mono_crash.* 18 | 19 | # Build results 20 | [Dd]ebug/ 21 | [Dd]ebugPublic/ 22 | [Rr]elease/ 23 | [Rr]eleases/ 24 | x64/ 25 | x86/ 26 | [Ww][Ii][Nn]32/ 27 | [Aa][Rr][Mm]/ 28 | [Aa][Rr][Mm]64/ 29 | bld/ 30 | [Bb]in/ 31 | [Oo]bj/ 32 | [Oo]ut/ 33 | [Ll]og/ 34 | [Ll]ogs/ 35 | 36 | # Visual Studio 2015/2017 cache/options directory 37 | .vs/ 38 | # Uncomment if you have tasks that create the project's static files in wwwroot 39 | #wwwroot/ 40 | 41 | # Visual Studio 2017 auto generated files 42 | Generated\ Files/ 43 | 44 | # MSTest test Results 45 | [Tt]est[Rr]esult*/ 46 | [Bb]uild[Ll]og.* 47 | 48 | # NUnit 49 | *.VisualState.xml 50 | TestResult.xml 51 | nunit-*.xml 52 | 53 | # Build Results of an ATL Project 54 | [Dd]ebugPS/ 55 | [Rr]eleasePS/ 56 | dlldata.c 57 | 58 | # Benchmark Results 59 | BenchmarkDotNet.Artifacts/ 60 | 61 | # .NET Core 62 | project.lock.json 63 | project.fragment.lock.json 64 | artifacts/ 65 | 66 | # ASP.NET Scaffolding 67 | ScaffoldingReadMe.txt 68 | 69 | # StyleCop 70 | StyleCopReport.xml 71 | 72 | # Files built by Visual Studio 73 | *_i.c 74 | *_p.c 75 | *_h.h 76 | *.ilk 77 | *.meta 78 | *.obj 79 | *.iobj 80 | *.pch 81 | *.pdb 82 | *.ipdb 83 | *.pgc 84 | *.pgd 85 | *.rsp 86 | *.sbr 87 | *.tlb 88 | *.tli 89 | *.tlh 90 | *.tmp 91 | *.tmp_proj 92 | *_wpftmp.csproj 93 | *.log 94 | *.vspscc 95 | *.vssscc 96 | .builds 97 | *.pidb 98 | *.svclog 99 | *.scc 100 | 101 | # Chutzpah Test files 102 | _Chutzpah* 103 | 104 | # Visual C++ cache files 105 | ipch/ 106 | *.aps 107 | *.ncb 108 | *.opendb 109 | *.opensdf 110 | *.sdf 111 | *.cachefile 112 | *.VC.db 113 | *.VC.VC.opendb 114 | 115 | # Visual Studio profiler 116 | *.psess 117 | *.vsp 118 | *.vspx 119 | *.sap 120 | 121 | # Visual Studio Trace Files 122 | *.e2e 123 | 124 | # TFS 2012 Local Workspace 125 | $tf/ 126 | 127 | # Guidance Automation Toolkit 128 | *.gpState 129 | 130 | # ReSharper is a .NET coding add-in 131 | _ReSharper*/ 132 | *.[Rr]e[Ss]harper 133 | *.DotSettings.user 134 | 135 | # TeamCity is a build add-in 136 | _TeamCity* 137 | 138 | # DotCover is a Code Coverage Tool 139 | *.dotCover 140 | 141 | # AxoCover is a Code Coverage Tool 142 | .axoCover/* 143 | !.axoCover/settings.json 144 | 145 | # Coverlet is a free, cross platform Code Coverage Tool 146 | coverage*.json 147 | coverage*.xml 148 | coverage*.info 149 | 150 | # Visual Studio code coverage results 151 | *.coverage 152 | *.coveragexml 153 | 154 | # NCrunch 155 | _NCrunch_* 156 | .*crunch*.local.xml 157 | nCrunchTemp_* 158 | 159 | # MightyMoose 160 | *.mm.* 161 | AutoTest.Net/ 162 | 163 | # Web workbench (sass) 164 | .sass-cache/ 165 | 166 | # Installshield output folder 167 | [Ee]xpress/ 168 | 169 | # DocProject is a documentation generator add-in 170 | DocProject/buildhelp/ 171 | DocProject/Help/*.HxT 172 | DocProject/Help/*.HxC 173 | DocProject/Help/*.hhc 174 | DocProject/Help/*.hhk 175 | DocProject/Help/*.hhp 176 | DocProject/Help/Html2 177 | DocProject/Help/html 178 | 179 | # Click-Once directory 180 | publish/ 181 | 182 | # Publish Web Output 183 | *.[Pp]ublish.xml 184 | *.azurePubxml 185 | # Note: Comment the next line if you want to checkin your web deploy settings, 186 | # but database connection strings (with potential passwords) will be unencrypted 187 | *.pubxml 188 | *.publishproj 189 | 190 | # Microsoft Azure Web App publish settings. Comment the next line if you want to 191 | # checkin your Azure Web App publish settings, but sensitive information contained 192 | # in these scripts will be unencrypted 193 | PublishScripts/ 194 | 195 | # NuGet Packages 196 | *.nupkg 197 | # NuGet Symbol Packages 198 | *.snupkg 199 | # The packages folder can be ignored because of Package Restore 200 | **/[Pp]ackages/* 201 | # except build/, which is used as an MSBuild target. 202 | !**/[Pp]ackages/build/ 203 | # Uncomment if necessary however generally it will be regenerated when needed 204 | #!**/[Pp]ackages/repositories.config 205 | # NuGet v3's project.json files produces more ignorable files 206 | *.nuget.props 207 | *.nuget.targets 208 | 209 | # Microsoft Azure Build Output 210 | csx/ 211 | *.build.csdef 212 | 213 | # Microsoft Azure Emulator 214 | ecf/ 215 | rcf/ 216 | 217 | # Windows Store app package directories and files 218 | AppPackages/ 219 | BundleArtifacts/ 220 | Package.StoreAssociation.xml 221 | _pkginfo.txt 222 | *.appx 223 | *.appxbundle 224 | *.appxupload 225 | 226 | # Visual Studio cache files 227 | # files ending in .cache can be ignored 228 | *.[Cc]ache 229 | # but keep track of directories ending in .cache 230 | !?*.[Cc]ache/ 231 | 232 | # Others 233 | ClientBin/ 234 | ~$* 235 | *~ 236 | *.dbmdl 237 | *.dbproj.schemaview 238 | *.jfm 239 | *.pfx 240 | *.publishsettings 241 | orleans.codegen.cs 242 | 243 | # Including strong name files can present a security risk 244 | # (https://github.com/github/gitignore/pull/2483#issue-259490424) 245 | #*.snk 246 | 247 | # Since there are multiple workflows, uncomment next line to ignore bower_components 248 | # (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) 249 | #bower_components/ 250 | 251 | # RIA/Silverlight projects 252 | Generated_Code/ 253 | 254 | # Backup & report files from converting an old project file 255 | # to a newer Visual Studio version. Backup files are not needed, 256 | # because we have git ;-) 257 | _UpgradeReport_Files/ 258 | Backup*/ 259 | UpgradeLog*.XML 260 | UpgradeLog*.htm 261 | ServiceFabricBackup/ 262 | *.rptproj.bak 263 | 264 | # SQL Server files 265 | *.mdf 266 | *.ldf 267 | *.ndf 268 | 269 | # Business Intelligence projects 270 | *.rdl.data 271 | *.bim.layout 272 | *.bim_*.settings 273 | *.rptproj.rsuser 274 | *- [Bb]ackup.rdl 275 | *- [Bb]ackup ([0-9]).rdl 276 | *- [Bb]ackup ([0-9][0-9]).rdl 277 | 278 | # Microsoft Fakes 279 | FakesAssemblies/ 280 | 281 | # GhostDoc plugin setting file 282 | *.GhostDoc.xml 283 | 284 | # Node.js Tools for Visual Studio 285 | .ntvs_analysis.dat 286 | node_modules/ 287 | 288 | # Visual Studio 6 build log 289 | *.plg 290 | 291 | # Visual Studio 6 workspace options file 292 | *.opt 293 | 294 | # Visual Studio 6 auto-generated workspace file (contains which files were open etc.) 295 | *.vbw 296 | 297 | # Visual Studio LightSwitch build output 298 | **/*.HTMLClient/GeneratedArtifacts 299 | **/*.DesktopClient/GeneratedArtifacts 300 | **/*.DesktopClient/ModelManifest.xml 301 | **/*.Server/GeneratedArtifacts 302 | **/*.Server/ModelManifest.xml 303 | _Pvt_Extensions 304 | 305 | # Paket dependency manager 306 | .paket/paket.exe 307 | paket-files/ 308 | 309 | # FAKE - F# Make 310 | .fake/ 311 | 312 | # CodeRush personal settings 313 | .cr/personal 314 | 315 | # Python Tools for Visual Studio (PTVS) 316 | __pycache__/ 317 | *.pyc 318 | 319 | # Cake - Uncomment if you are using it 320 | # tools/** 321 | # !tools/packages.config 322 | 323 | # Tabs Studio 324 | *.tss 325 | 326 | # Telerik's JustMock configuration file 327 | *.jmconfig 328 | 329 | # BizTalk build output 330 | *.btp.cs 331 | *.btm.cs 332 | *.odx.cs 333 | *.xsd.cs 334 | 335 | # OpenCover UI analysis results 336 | OpenCover/ 337 | 338 | # Azure Stream Analytics local run output 339 | ASALocalRun/ 340 | 341 | # MSBuild Binary and Structured Log 342 | *.binlog 343 | 344 | # NVidia Nsight GPU debugger configuration file 345 | *.nvuser 346 | 347 | # MFractors (Xamarin productivity tool) working folder 348 | .mfractor/ 349 | 350 | # Local History for Visual Studio 351 | .localhistory/ 352 | 353 | # BeatPulse healthcheck temp database 354 | healthchecksdb 355 | 356 | # Backup folder for Package Reference Convert tool in Visual Studio 2017 357 | MigrationBackup/ 358 | 359 | # Ionide (cross platform F# VS Code tools) working folder 360 | .ionide/ 361 | 362 | # Fody - auto-generated XML schema 363 | FodyWeavers.xsd -------------------------------------------------------------------------------- /LICENSE.txt: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2024 sumrix 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # ![Icon](images/icon_32x32.png) ConsolePlot 2 | 3 | ConsolePlot is a .NET library for creating customizable line charts in the console. 4 | 5 | Complete documentation is available at the [API documentation](docs/API.md). 6 | 7 | [![Latest version](https://img.shields.io/nuget/v/ConsolePlot.svg)](https://www.nuget.org/packages/ConsolePlot) 8 | 9 | ## Quick Start 10 | 11 | To use ConsolePlot, first install the [NuGet Package](https://www.nuget.org/packages/ConsolePlot): 12 | 13 | ```sh 14 | dotnet add package ConsolePlot 15 | ``` 16 | 17 | Here's a simple example to get you started: 18 | 19 | ```csharp 20 | using ConsolePlot; 21 | 22 | Console.OutputEncoding = System.Text.Encoding.UTF8; 23 | 24 | double[] xs = [1, 2, 3, 4, 5]; 25 | double[] ys = [1, 4, 9, 16, 25]; 26 | 27 | Plot plt = new Plot(80, 22); 28 | plt.AddSeries(xs, ys); 29 | plt.Draw(); 30 | plt.Render(); 31 | ``` 32 | 33 | This will create a simple plot in your console: 34 | 35 | Simple Plot 36 | 37 | ## Features 38 | 39 | - Customizable axis, grid, ticks and chart lines. 40 | - Support for multiple data series. 41 | - Adaptive scaling: automatically adjusts the plot to fit the console window, ensuring round axis labels, optimal tick placement, and alignment with console cells. 42 | 43 | ## Examples 44 | 45 | You can find various usage examples in the [ConsolePlot.Examples](src/ConsolePlot.Examples) project. 46 | 47 | ### Running Examples in Visual Studio: 48 | 1. Clone this repository by clicking "Open with Visual Studio" on the GitHub page. 49 | 2. Open the solution and set `ConsolePlot.Examples` as the startup project. 50 | 3. Run the project. 51 | 52 | ### Running Examples from the Command Line: 53 | ```sh 54 | git clone https://github.com/sumrix/ConsolePlot.git 55 | cd ./ConsolePlot/src 56 | dotnet build 57 | dotnet run --project ConsolePlot.Examples 58 | ``` 59 | 60 | ## Contributing 61 | 62 | Bug reports and contributions are welcome. Please submit them via the [Issues](https://github.com/Sumrix/ConsolePlot/issues) or [Pull Requests](https://github.com/Sumrix/ConsolePlot/pulls). -------------------------------------------------------------------------------- /docs/API.md: -------------------------------------------------------------------------------- 1 | # ConsolePlot API Documentation 2 | 3 | ## Plot Class 4 | 5 | The `Plot` class is the main entry point for creating and customizing plots. 6 | 7 | ```csharp 8 | public class Plot 9 | { 10 | public Plot(int width, int height); 11 | 12 | public AxisSettings Axis { get; } 13 | public GridSettings Grid { get; } 14 | public TickSettings Ticks { get; } 15 | public List Series { get; } 16 | 17 | public Series AddSeries(IReadOnlyCollection xs, IReadOnlyCollection ys, PointPen? pen = null); 18 | public void Draw(); 19 | public ConsoleImage GetImage(); 20 | public void Render(); 21 | } 22 | ``` 23 | 24 | ### Constructor 25 | 26 | - `Plot(int width, int height)`: Creates a new plot with the specified width and height. 27 | 28 | ### Properties 29 | 30 | - `Axis`: Gets the axis settings for the plot. 31 | - `Grid`: Gets the grid settings for the plot. 32 | - `Ticks`: Gets the tick settings for the plot. 33 | - `Series`: Gets the collection of data series added to the plot. 34 | 35 | ### Methods 36 | 37 | - `AddSeries(IReadOnlyCollection xs, IReadOnlyCollection ys, PointPen? pen = null)`: Adds a new series to the plot. Returns the created `Series` object. 38 | - `Draw()`: Prepares the plot image. 39 | - `GetImage()`: Returns the `ConsoleImage` object representing the plot. 40 | - `Render()`: Renders the plot to the console. 41 | 42 | ## AxisSettings Class 43 | 44 | ```csharp 45 | public class AxisSettings 46 | { 47 | public bool IsVisible { get; set; } 48 | public LinePen Pen { get; set; } 49 | } 50 | ``` 51 | 52 | - `IsVisible`: Determines whether the axis is visible. 53 | - `Pen`: The pen used to draw the axis. 54 | 55 | ## GridSettings Class 56 | 57 | ```csharp 58 | public class GridSettings 59 | { 60 | public bool IsVisible { get; set; } 61 | public LinePen Pen { get; set; } 62 | } 63 | ``` 64 | 65 | - `IsVisible`: Determines whether the grid is visible. 66 | - `Pen`: The pen used to draw the grid. 67 | 68 | ## TickSettings Class 69 | 70 | ```csharp 71 | public class TickSettings 72 | { 73 | public bool IsVisible { get; set; } 74 | public LinePen Pen { get; set; } 75 | public int DesiredXStep { get; set; } 76 | public int DesiredYStep { get; set; } 77 | public LabelSettings Labels { get; } 78 | } 79 | ``` 80 | 81 | - `IsVisible`: Determines whether ticks are visible. 82 | - `Pen`: The pen used to draw the ticks. 83 | - `DesiredXStep`: The desired step between ticks on the x-axis. 84 | - `DesiredYStep`: The desired step between ticks on the y-axis. 85 | - `Labels`: Gets the label settings for the ticks. 86 | 87 | ## LabelSettings Class 88 | 89 | ```csharp 90 | public class LabelSettings 91 | { 92 | public bool IsVisible { get; set; } 93 | public ConsoleColor Color { get; set; } 94 | public bool AttachToAxis { get; set; } 95 | public string Format { get; set; } 96 | } 97 | ``` 98 | 99 | - `IsVisible`: Determines whether labels are visible. 100 | - `Color`: The color of the labels. 101 | - `AttachToAxis`: Determines whether labels should be attached to the axis. 102 | - `Format`: The string format used for label values. 103 | 104 | ## Drawing Tools 105 | 106 | ### SystemLineBrushes 107 | 108 | ```csharp 109 | public static class SystemLineBrushes 110 | { 111 | public static LineBrush Thin { get; } 112 | public static LineBrush Bold { get; } 113 | public static LineBrush Double { get; } 114 | public static LineBrush Dotted { get; } 115 | public static LineBrush DottedBold { get; } 116 | public static LineBrush Dashed { get; } 117 | public static LineBrush DashedBold { get; } 118 | } 119 | ``` 120 | 121 | Provides a set of predefined line brushes for various line styles. 122 | 123 | ### SystemPointBrushes 124 | 125 | ```csharp 126 | public static class SystemPointBrushes 127 | { 128 | public static IPointBrush Braille { get; } 129 | public static IPointBrush Quadrant { get; } 130 | public static ConsolePointBrush Block { get; } 131 | public static ConsolePointBrush Star { get; } 132 | public static ConsolePointBrush Dot { get; } 133 | } 134 | ``` 135 | 136 | Provides a set of predefined point brushes for various point styles. 137 | 138 | ### LinePen and PointPen 139 | 140 | ```csharp 141 | public class LinePen 142 | { 143 | public LineBrush Brush { get; } 144 | public ConsoleColor Color { get; } 145 | 146 | public LinePen(LineBrush brush, ConsoleColor color); 147 | } 148 | 149 | public class PointPen 150 | { 151 | public IPointBrush Brush { get; } 152 | public ConsoleColor Color { get; } 153 | 154 | public PointPen(IPointBrush brush, ConsoleColor color); 155 | } 156 | ``` 157 | 158 | `LinePen` and `PointPen` are used to define the appearance of lines and points in the plot. 159 | 160 | ## Usage Example 161 | 162 | ```csharp 163 | using ConsolePlot; 164 | using ConsolePlot.Drawing.Tools; 165 | 166 | Console.OutputEncoding = System.Text.Encoding.UTF8; 167 | 168 | var plt = new Plot(80, 22); 169 | 170 | var xs = Enumerable.Range(-30, 61).Select(i => i * 0.1).ToArray(); 171 | var ys = xs.Select(Math.Sin).ToArray(); 172 | 173 | plt.AddSeries(xs, ys, new PointPen(SystemPointBrushes.Braille, ConsoleColor.Blue)); 174 | 175 | plt.Axis.IsVisible = true; 176 | plt.Grid.IsVisible = true; 177 | plt.Ticks.IsVisible = true; 178 | plt.Ticks.Labels.IsVisible = true; 179 | 180 | plt.Draw(); 181 | plt.Render(); 182 | ``` 183 | 184 | This example creates a simple sine wave plot with customized settings. -------------------------------------------------------------------------------- /docs/nuget_readme.md: -------------------------------------------------------------------------------- 1 | ## About 2 | 3 | ConsolePlot is a .NET library for creating ASCII plots in the console. 4 | 5 | More documenation is available at the [API documentation](https://github.com/Sumrix/ConsolePlot/blob/master/docs/API.md). 6 | 7 | ## Quick Start 8 | 9 | Here's a simple example to get you started: 10 | 11 | ```csharp 12 | using ConsolePlot; 13 | 14 | Console.OutputEncoding = System.Text.Encoding.UTF8; 15 | 16 | double[] xs = [1, 2, 3, 4, 5]; 17 | double[] ys = [1, 4, 9, 16, 25]; 18 | 19 | Plot plt = new Plot(80, 22); 20 | plt.AddSeries(xs, ys); 21 | plt.Draw(); 22 | plt.Render(); 23 | ``` 24 | 25 | This will create a simple plot in your console: 26 | 27 | ![Simple Plot](https://raw.githubusercontent.com/Sumrix/ConsolePlot/refs/heads/master/images/nuget_quickstart_console.png) 28 | 29 | More examples in the [ConsolePlot.Examples](https://github.com/Sumrix/ConsolePlot/tree/master/src/ConsolePlot.Examples) project. 30 | 31 | ## Features 32 | 33 | - Customizable axis, grid, ticks and chart lines. 34 | - Support for multiple data series. 35 | - Adaptive scaling: automatically adjusts the plot to fit the console window, ensuring round axis labels, optimal tick placement, and alignment with console cells. 36 | 37 | ## Feedback 38 | 39 | Bug reports and contributions are welcome at the [GitHub repository](https://github.com/Sumrix/ConsolePlot/). -------------------------------------------------------------------------------- /images/icon_128x128.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Sumrix/ConsolePlot/400ef430bd4f1e66fba2886a3a94433b6a4bf10a/images/icon_128x128.png -------------------------------------------------------------------------------- /images/icon_32x32.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Sumrix/ConsolePlot/400ef430bd4f1e66fba2886a3a94433b6a4bf10a/images/icon_32x32.png -------------------------------------------------------------------------------- /images/nuget_quickstart_console.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Sumrix/ConsolePlot/400ef430bd4f1e66fba2886a3a94433b6a4bf10a/images/nuget_quickstart_console.png -------------------------------------------------------------------------------- /images/quickstart_console.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Sumrix/ConsolePlot/400ef430bd4f1e66fba2886a3a94433b6a4bf10a/images/quickstart_console.png -------------------------------------------------------------------------------- /src/ConsolePlot.Examples/ConsolePlot.Examples.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | Exe 5 | net8.0 6 | enable 7 | enable 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | -------------------------------------------------------------------------------- /src/ConsolePlot.Examples/Program.cs: -------------------------------------------------------------------------------- 1 | using ConsolePlot.Drawing.Tools; 2 | 3 | namespace ConsolePlot.Examples; 4 | 5 | internal static class Program 6 | { 7 | private static void Main() 8 | { 9 | while (true) 10 | { 11 | Console.Clear(); 12 | Console.WriteLine("Choose an example to run:"); 13 | Console.WriteLine("1. Basic Example"); 14 | Console.WriteLine("2. Multiple Series Example"); 15 | Console.WriteLine("3. All Settings Demonstration"); 16 | Console.WriteLine("4. Non-Unicode Output Example"); 17 | Console.WriteLine("5. Exit"); 18 | 19 | var choice = Console.ReadLine(); 20 | switch (choice) 21 | { 22 | case "1": 23 | BasicExample(); 24 | break; 25 | case "2": 26 | MultipleSeries(); 27 | break; 28 | case "3": 29 | AllSettingsDemonstration(); 30 | break; 31 | case "4": 32 | NonUnicodeExample(); 33 | break; 34 | case "5": 35 | return; 36 | default: 37 | Console.WriteLine("Invalid choice"); 38 | break; 39 | } 40 | 41 | Console.WriteLine("Press any key to continue..."); 42 | Console.ReadKey(); 43 | } 44 | } 45 | 46 | private static void BasicExample() 47 | { 48 | Console.OutputEncoding = System.Text.Encoding.UTF8; 49 | 50 | // Create a new plot with width 80 and height 22 51 | var plt = new Plot(80, 22); 52 | 53 | // Generate some sample data 54 | double[] xs = [1, 2, 3, 4, 5]; 55 | double[] ys = [1, 4, 9, 16, 25]; 56 | 57 | // Add the data series to the plot 58 | plt.AddSeries(xs, ys); 59 | 60 | // Draw the plot (prepare the image) 61 | plt.Draw(); 62 | 63 | // Render the plot to the console 64 | plt.Render(); 65 | } 66 | 67 | private static void MultipleSeries() 68 | { 69 | Console.OutputEncoding = System.Text.Encoding.UTF8; 70 | 71 | var plt = new Plot(80, 22); 72 | 73 | // Generate x values from -3 to 3 with 0.1 step 74 | var xs = Enumerable.Range(-30, 61).Select(i => i * 0.1).ToArray(); 75 | 76 | // Calculate sin(x) values 77 | var sinYs = xs.Select(Math.Sin).ToArray(); 78 | 79 | // Calculate 1/x values, replacing infinity with NaN and limiting the range 80 | var reciprocalYs = xs.Select(x => { 81 | if (x == 0 ) return double.NaN; 82 | var y = 1 / x; 83 | // Limit the range of y values 84 | return y is > 3 or < -3 ? double.NaN : y; 85 | }).ToArray(); 86 | 87 | // Add sin(x) series with blue color 88 | plt.AddSeries(xs, sinYs, new PointPen(SystemPointBrushes.Braille, ConsoleColor.Blue)); 89 | 90 | // Add 1/x series with red color 91 | plt.AddSeries(xs, reciprocalYs, new PointPen(SystemPointBrushes.Braille, ConsoleColor.Red)); 92 | 93 | plt.Draw(); 94 | plt.Render(); 95 | 96 | Console.WriteLine("Blue: sin(x)"); 97 | Console.WriteLine("Red: 1/x (limited to range [-3, 3])"); 98 | } 99 | 100 | private static void AllSettingsDemonstration() 101 | { 102 | Console.OutputEncoding = System.Text.Encoding.UTF8; 103 | 104 | var plt = new Plot(80, 22); 105 | 106 | // Axis settings 107 | plt.Axis.IsVisible = true; 108 | plt.Axis.Pen = new LinePen(SystemLineBrushes.Double, ConsoleColor.Yellow); 109 | 110 | // Grid settings 111 | plt.Grid.IsVisible = true; 112 | plt.Grid.Pen = new LinePen(SystemLineBrushes.Dotted, ConsoleColor.DarkGray); 113 | 114 | // Tick settings 115 | plt.Ticks.IsVisible = true; 116 | plt.Ticks.Pen = new LinePen(SystemLineBrushes.Thin, ConsoleColor.Cyan); 117 | plt.Ticks.DesiredXStep = 10; 118 | plt.Ticks.DesiredYStep = 5; 119 | 120 | // Label settings 121 | plt.Ticks.Labels.IsVisible = true; 122 | plt.Ticks.Labels.Color = ConsoleColor.Green; 123 | plt.Ticks.Labels.AttachToAxis = false; 124 | plt.Ticks.Labels.Format = "F2"; 125 | 126 | // Generate sample data 127 | var xs = Enumerable.Range(0, 100).Select(i => i * 0.1).ToArray(); 128 | var ys = xs.Select(x => Math.Sin(x) * Math.Exp(-x * 0.1)).ToArray(); 129 | 130 | // Add data series with custom point style 131 | plt.AddSeries(xs, ys, new PointPen(SystemPointBrushes.Star, ConsoleColor.Magenta)); 132 | 133 | plt.Draw(); 134 | plt.Render(); 135 | } 136 | 137 | private static void NonUnicodeExample() 138 | { 139 | // Note: We're not setting Console.OutputEncoding here 140 | 141 | var plt = new Plot(80, 22); 142 | 143 | // Use non-Unicode line brush 144 | var nonUnicodeBrush = new LineBrush('|', '-', '+'); 145 | 146 | // Axis settings 147 | plt.Axis.IsVisible = true; 148 | plt.Axis.Pen = new LinePen(nonUnicodeBrush, ConsoleColor.White); 149 | 150 | // Grid settings 151 | plt.Grid.IsVisible = true; 152 | plt.Grid.Pen = new LinePen(nonUnicodeBrush, ConsoleColor.DarkGray); 153 | 154 | // Tick settings 155 | plt.Ticks.IsVisible = true; 156 | plt.Ticks.Pen = new LinePen(nonUnicodeBrush, ConsoleColor.White); 157 | 158 | // Generate sample data 159 | var xs = Enumerable.Range(0, 50).Select(i => i * 0.2).ToArray(); 160 | var ys = xs.Select(Math.Sin).ToArray(); 161 | 162 | // Add data series with Star point style (non-Unicode) 163 | plt.AddSeries(xs, ys, new PointPen(SystemPointBrushes.Star, ConsoleColor.Yellow)); 164 | 165 | plt.Draw(); 166 | plt.Render(); 167 | } 168 | } -------------------------------------------------------------------------------- /src/ConsolePlot.sln: -------------------------------------------------------------------------------- 1 | Microsoft Visual Studio Solution File, Format Version 12.00 2 | # Visual Studio Version 17 3 | VisualStudioVersion = 17.12.35309.182 4 | MinimumVisualStudioVersion = 10.0.40219.1 5 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ConsolePlot", "ConsolePlot\ConsolePlot.csproj", "{72F22F3A-9EC6-4CCD-981F-BF52EE3842B5}" 6 | EndProject 7 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ConsolePlot.Examples", "ConsolePlot.Examples\ConsolePlot.Examples.csproj", "{BB780ED0-59CC-4B9D-BBA3-54E5060AD1B3}" 8 | EndProject 9 | Global 10 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 11 | Debug|Any CPU = Debug|Any CPU 12 | Release|Any CPU = Release|Any CPU 13 | EndGlobalSection 14 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 15 | {72F22F3A-9EC6-4CCD-981F-BF52EE3842B5}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 16 | {72F22F3A-9EC6-4CCD-981F-BF52EE3842B5}.Debug|Any CPU.Build.0 = Debug|Any CPU 17 | {72F22F3A-9EC6-4CCD-981F-BF52EE3842B5}.Release|Any CPU.ActiveCfg = Release|Any CPU 18 | {72F22F3A-9EC6-4CCD-981F-BF52EE3842B5}.Release|Any CPU.Build.0 = Release|Any CPU 19 | {BB780ED0-59CC-4B9D-BBA3-54E5060AD1B3}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 20 | {BB780ED0-59CC-4B9D-BBA3-54E5060AD1B3}.Debug|Any CPU.Build.0 = Debug|Any CPU 21 | {BB780ED0-59CC-4B9D-BBA3-54E5060AD1B3}.Release|Any CPU.ActiveCfg = Release|Any CPU 22 | {BB780ED0-59CC-4B9D-BBA3-54E5060AD1B3}.Release|Any CPU.Build.0 = Release|Any CPU 23 | EndGlobalSection 24 | GlobalSection(SolutionProperties) = preSolution 25 | HideSolutionNode = FALSE 26 | EndGlobalSection 27 | GlobalSection(ExtensibilityGlobals) = postSolution 28 | SolutionGuid = {53128A36-3A91-4C24-ACD2-7EADBFEED138} 29 | EndGlobalSection 30 | EndGlobal 31 | -------------------------------------------------------------------------------- /src/ConsolePlot/ConsolePlot.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | netstandard2.0 5 | Sumrix 6 | https://github.com/Sumrix/ConsolePlot 7 | nuget_readme.md 8 | https://github.com/Sumrix/ConsolePlot.git 9 | console;terminal;plot;chart 10 | Copyright © 2024 Sumrix 11 | MIT 12 | ConsolePlot creates customizable line charts. 13 | git 14 | icon_128x128.png 15 | true 16 | true 17 | True 18 | I did this and that 19 | 20 | 21 | 22 | true 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | True 32 | \ 33 | 34 | 35 | True 36 | \ 37 | 38 | 39 | 40 | 41 | -------------------------------------------------------------------------------- /src/ConsolePlot/Drawing/AbstractGraphics.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace ConsolePlot.Drawing 4 | { 5 | /// 6 | /// Represents an abstract base class for graphics operations. 7 | /// 8 | /// The type of pen used for drawing operations. 9 | public abstract class AbstractGraphics 10 | { 11 | /// 12 | /// Represents the console image where graphics operations are drawn. 13 | /// 14 | protected readonly ConsoleImage Image; 15 | private Rectangle _clipBounds; 16 | 17 | /// 18 | /// Gets or sets the clipping bounds for drawing operations. 19 | /// 20 | public Rectangle ClipBounds 21 | { 22 | get => _clipBounds; 23 | set => SetClip(value); 24 | } 25 | 26 | /// 27 | /// Gets the height of the image. 28 | /// 29 | public int ImageHeight { get; } 30 | 31 | /// 32 | /// Gets the width of the image. 33 | /// 34 | public int ImageWidth { get; } 35 | 36 | /// 37 | /// Initializes a new instance of the class. 38 | /// 39 | /// The image to draw on. 40 | /// The width of the image. 41 | /// The height of the image. 42 | protected AbstractGraphics(ConsoleImage image, int imageWidth, int imageHeight) 43 | { 44 | Image = image; 45 | _clipBounds = new Rectangle(0, 0, imageWidth, imageHeight); 46 | ImageWidth = imageWidth; 47 | ImageHeight = imageHeight; 48 | } 49 | 50 | /// 51 | /// Clears the entire image with the specified character and color. 52 | /// 53 | /// The character to fill the image with. 54 | /// The color to use for filling. 55 | public void Clear(char clearChar = ' ', ConsoleColor clearColor = ConsoleColor.White) 56 | { 57 | for (var y = 0; y <= Image.Height; y++) 58 | { 59 | for (var x = 0; x <= Image.Width; x++) 60 | { 61 | Image.SetPixel(x, y, clearChar, clearColor); 62 | } 63 | } 64 | } 65 | 66 | /// 67 | /// Gets the underlying . 68 | /// 69 | /// The this graphics context is drawing on. 70 | public ConsoleImage GetImage() => Image; 71 | 72 | /// 73 | /// Resets the clipping rectangle to the full image bounds. 74 | /// 75 | public void ResetClip() 76 | { 77 | _clipBounds = new Rectangle(0, 0, ImageWidth, ImageHeight); 78 | } 79 | 80 | /// 81 | /// Sets the clipping rectangle for drawing operations. 82 | /// 83 | /// The new clipping rectangle. 84 | public void SetClip(Rectangle clip) 85 | { 86 | var x = Math.Max(0, clip.X); 87 | var y = Math.Max(0, clip.Y); 88 | var width = Math.Min(clip.Width, ImageWidth - x); 89 | var height = Math.Min(clip.Height, ImageHeight - y); 90 | 91 | _clipBounds = new Rectangle(x, y, width, height); 92 | } 93 | 94 | /// 95 | /// Draws a line connecting two points specified by the coordinate pairs. 96 | /// 97 | /// Pen that determines the color and style of the line. 98 | /// The x-coordinate of the first point. 99 | /// The y-coordinate of the first point. 100 | /// The x-coordinate of the second point. 101 | /// The y-coordinate of the second point. 102 | protected void DrawLineCore(TPen pen, int x1, int y1, int x2, int y2) 103 | { 104 | if (!ClipLine(ref x1, ref y1, ref x2, ref y2)) 105 | { 106 | return; // Line is completely outside the clipping bounds 107 | } 108 | 109 | var dx = Math.Abs(x2 - x1); 110 | var dy = Math.Abs(y2 - y1); 111 | var sx = x1 < x2 ? 1 : -1; 112 | var sy = y1 < y2 ? 1 : -1; 113 | var err = dx - dy; 114 | 115 | while (true) 116 | { 117 | DrawPointCore(pen, x1, y1); 118 | if (x1 == x2 && y1 == y2) 119 | { 120 | break; 121 | } 122 | 123 | var e2 = 2 * err; 124 | if (e2 > -dy) 125 | { 126 | err -= dy; 127 | x1 += sx; 128 | } 129 | 130 | if (e2 < dx) 131 | { 132 | err += dx; 133 | y1 += sy; 134 | } 135 | } 136 | } 137 | 138 | /// 139 | /// Draws a single point at the specified coordinates. 140 | /// 141 | /// The pen that determines the color and style of the point. 142 | /// The x-coordinate of the point. 143 | /// The y-coordinate of the point. 144 | protected abstract void DrawPointCore(TPen pen, int x, int y); 145 | 146 | private bool ClipLine(ref int x1, ref int y1, ref int x2, ref int y2) 147 | { 148 | // Cohen-Sutherland line clipping algorithm 149 | const int INSIDE = 0; // 0000 150 | const int LEFT = 1; // 0001 151 | const int RIGHT = 2; // 0010 152 | const int BOTTOM = 4; // 0100 153 | const int TOP = 8; // 1000 154 | 155 | int ComputeOutCode(int x, int y) 156 | { 157 | var code = INSIDE; 158 | if (x < _clipBounds.Left) 159 | { 160 | code |= LEFT; 161 | } 162 | else if (x > _clipBounds.Right) 163 | { 164 | code |= RIGHT; 165 | } 166 | 167 | if (y < _clipBounds.Bottom) 168 | { 169 | code |= BOTTOM; 170 | } 171 | else if (y > _clipBounds.Top) 172 | { 173 | code |= TOP; 174 | } 175 | 176 | return code; 177 | } 178 | 179 | var outcode1 = ComputeOutCode(x1, y1); 180 | var outcode2 = ComputeOutCode(x2, y2); 181 | var accept = false; 182 | 183 | while (true) 184 | { 185 | if ((outcode1 | outcode2) == 0) 186 | { 187 | accept = true; 188 | break; 189 | } 190 | 191 | if ((outcode1 & outcode2) != 0) 192 | { 193 | break; 194 | } 195 | 196 | int x = 0, y = 0; 197 | var outcodeOut = outcode1 != 0 ? outcode1 : outcode2; 198 | 199 | if ((outcodeOut & TOP) != 0) 200 | { 201 | x = x1 + (x2 - x1) * (_clipBounds.Top - y1) / (y2 - y1); 202 | y = _clipBounds.Top; 203 | } 204 | else if ((outcodeOut & BOTTOM) != 0) 205 | { 206 | x = x1 + (x2 - x1) * (_clipBounds.Bottom - y1) / (y2 - y1); 207 | y = _clipBounds.Bottom; 208 | } 209 | else if ((outcodeOut & RIGHT) != 0) 210 | { 211 | y = y1 + (y2 - y1) * (_clipBounds.Right - x1) / (x2 - x1); 212 | x = _clipBounds.Right; 213 | } 214 | else if ((outcodeOut & LEFT) != 0) 215 | { 216 | y = y1 + (y2 - y1) * (_clipBounds.Left - x1) / (x2 - x1); 217 | x = _clipBounds.Left; 218 | } 219 | 220 | if (outcodeOut == outcode1) 221 | { 222 | x1 = x; 223 | y1 = y; 224 | outcode1 = ComputeOutCode(x1, y1); 225 | } 226 | else 227 | { 228 | x2 = x; 229 | y2 = y; 230 | outcode2 = ComputeOutCode(x2, y2); 231 | } 232 | } 233 | 234 | return accept; 235 | } 236 | } 237 | } -------------------------------------------------------------------------------- /src/ConsolePlot/Drawing/ConsoleGraphics.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using ConsolePlot.Drawing.Tools; 3 | 4 | namespace ConsolePlot.Drawing 5 | { 6 | /// 7 | /// Represents a graphics context for drawing directly onto a console using characters as pixels. 8 | /// 9 | public class ConsoleGraphics : AbstractGraphics 10 | { 11 | /// 12 | /// Initializes a new instance of the class with the specified image. 13 | /// 14 | /// The to draw on. 15 | public ConsoleGraphics(ConsoleImage image) : base(image, image.Width, image.Height) 16 | { 17 | } 18 | 19 | /// 20 | /// Draws a horizontal line between two x-coordinates at the specified y-coordinate. 21 | /// 22 | /// that determines the color and style of the line. 23 | /// The first x-coordinate. 24 | /// The second x-coordinate. 25 | /// The y-coordinate of the line. 26 | public void DrawHorizontal(LinePen pen, int x1, int x2, int y) 27 | { 28 | if (!ClipBounds.ContainsY(y)) 29 | { 30 | return; 31 | } 32 | 33 | if (x1 > x2) 34 | { 35 | (x1, x2) = (x2, x1); 36 | } 37 | 38 | var start = Math.Max(ClipBounds.Left, x1); 39 | var end = Math.Min(ClipBounds.Right, x2); 40 | 41 | for (var x = start; x <= end; x++) 42 | { 43 | DrawHorizontalCore(pen, x, x, y); 44 | } 45 | } 46 | 47 | /// 48 | /// Draws a horizontal line character at the specified coordinates. 49 | /// 50 | /// that determines the color and style of the line. 51 | /// The x-coordinate of the line character. 52 | /// The y-coordinate of the line character. 53 | public void DrawHorizontal(LinePen pen, int x, int y) 54 | { 55 | if (ClipBounds.Contains(x, y)) 56 | { 57 | DrawHorizontalCore(pen, x, x, y); 58 | } 59 | } 60 | 61 | /// 62 | /// Draws a horizontal line across the entire clipping area at the specified y-coordinate. 63 | /// 64 | /// that determines the color and style of the line. 65 | /// The y-coordinate of the line. 66 | public void DrawHorizontal(LinePen pen, int y) 67 | { 68 | if (ClipBounds.ContainsY(y)) 69 | { 70 | DrawHorizontalCore(pen, ClipBounds.Left, ClipBounds.Right, y); 71 | } 72 | } 73 | 74 | /// 75 | /// Draws a line connecting two points specified by the coordinate pairs. 76 | /// 77 | /// that determines the color and style of the line. 78 | /// The x-coordinate of the first point. 79 | /// The y-coordinate of the first point. 80 | /// The x-coordinate of the second point. 81 | /// The y-coordinate of the second point. 82 | public void DrawLine(ConsolePointPen pen, int x1, int y1, int x2, int y2) 83 | { 84 | DrawLineCore(pen, x1, y1, x2, y2); 85 | } 86 | 87 | /// 88 | /// Draws a single point at the specified coordinates. 89 | /// 90 | /// that determines the color and style of the point. 91 | /// The x-coordinate of the point. 92 | /// The y-coordinate of the point. 93 | public void DrawPoint(ConsolePointPen pen, int x, int y) 94 | { 95 | DrawPointCore(pen, x, y); 96 | } 97 | 98 | /// 99 | /// Draws the specified string at the specified location with the specified color and, 100 | /// optionally, in the specified direction while ensuring visibility if required. 101 | /// 102 | /// String to draw. 103 | /// The color of the text. 104 | /// The x-coordinate of the drawn text. 105 | /// The y-coordinate of the drawn text. 106 | /// The direction of the drawn text. 107 | /// Whether to ensure the entire text is visible within the image bounds. 108 | /// Thrown when the text exceeds image dimensions and ensureVisible is true. 109 | public void DrawString( 110 | string s, 111 | ConsoleColor color, 112 | int x, 113 | int y, 114 | TextDirection direction = TextDirection.Horizontal, 115 | bool ensureVisible = false) 116 | { 117 | if (ensureVisible) 118 | { 119 | if (direction == TextDirection.Horizontal) 120 | { 121 | if (s.Length > ClipBounds.Width) 122 | { 123 | throw new InvalidOperationException("Text length exceeds clipping width."); 124 | } 125 | 126 | x = Math.Min(Math.Max(x, ClipBounds.Left), ClipBounds.Right - s.Length + 1); 127 | y = Math.Min(Math.Max(y, ClipBounds.Bottom), ClipBounds.Top); 128 | } 129 | else 130 | { 131 | if (s.Length > ClipBounds.Height) 132 | { 133 | throw new InvalidOperationException("Text length exceeds clipping height."); 134 | } 135 | 136 | x = Math.Min(Math.Max(x, ClipBounds.Left), ClipBounds.Right); 137 | y = Math.Min(Math.Max(y, ClipBounds.Bottom + s.Length - 1), ClipBounds.Top); 138 | } 139 | } 140 | 141 | for (var i = 0; i < s.Length; i++) 142 | { 143 | var currentX = direction == TextDirection.Horizontal ? x + i : x; 144 | var currentY = direction == TextDirection.Horizontal ? y : y - i; 145 | 146 | if (ClipBounds.Contains(currentX, currentY)) 147 | { 148 | Image.SetPixel(currentX, currentY, s[i], color); 149 | } 150 | else if (ensureVisible) 151 | { 152 | break; // Stop drawing if out of bounds and visibility is ensured 153 | } 154 | } 155 | } 156 | 157 | /// 158 | /// Draws a vertical line between two y-coordinates at the specified x-coordinate. 159 | /// 160 | /// that determines the color and style of the line. 161 | /// The x-coordinate of the line. 162 | /// The first y-coordinate of the line. 163 | /// The second y-coordinate of the line. 164 | public void DrawVertical(LinePen pen, int x, int y1, int y2) 165 | { 166 | if (!ClipBounds.ContainsX(x)) 167 | { 168 | return; 169 | } 170 | 171 | if (y1 > y2) 172 | { 173 | (y1, y2) = (y2, y1); 174 | } 175 | 176 | var start = Math.Max(ClipBounds.Bottom, y1); 177 | var end = Math.Min(ClipBounds.Top, y2); 178 | 179 | for (var y = start; y <= end; y++) 180 | { 181 | DrawVerticalCore(pen, x, y, y); 182 | } 183 | } 184 | 185 | /// 186 | /// Draws a vertical line character at the specified coordinates. 187 | /// 188 | /// that determines the color and style of the line. 189 | /// The x-coordinate of the line character. 190 | /// The y-coordinate of the line character. 191 | public void DrawVertical(LinePen pen, int x, int y) 192 | { 193 | if (ClipBounds.Contains(x, y)) 194 | { 195 | DrawVerticalCore(pen, x, y, y); 196 | } 197 | } 198 | 199 | /// 200 | /// Draws a vertical line across the entire clipping area at the specified x-coordinate. 201 | /// 202 | /// that determines the color and style of the line. 203 | /// The x-coordinate of the line. 204 | public void DrawVertical(LinePen pen, int x) 205 | { 206 | if (ClipBounds.ContainsX(x)) 207 | { 208 | DrawVerticalCore(pen, x, ClipBounds.Bottom, ClipBounds.Top); 209 | } 210 | } 211 | 212 | /// 213 | protected override void DrawPointCore(ConsolePointPen pen, int x, int y) 214 | { 215 | if (ClipBounds.Contains(x, y)) 216 | { 217 | Image.SetPixel(x, y, pen.Brush.PointChar, pen.Color); 218 | } 219 | } 220 | 221 | private void DrawHorizontalCore(LinePen pen, int start, int end, int y) 222 | { 223 | for (var x = start; x <= end; x++) 224 | { 225 | var pixel = Image.GetPixel(x, y); 226 | var symbol = pixel.Character == pen.Brush.Vertical || pixel.Character == pen.Brush.Cross 227 | ? pen.Brush.Cross 228 | : pen.Brush.Horizontal; 229 | Image.SetPixel(x, y, symbol, pen.Color); 230 | } 231 | } 232 | 233 | private void DrawVerticalCore(LinePen pen, int x, int start, int end) 234 | { 235 | for (var y = start; y <= end; y++) 236 | { 237 | var pixel = Image.GetPixel(x, y); 238 | var symbol = pixel.Character == pen.Brush.Horizontal || pixel.Character == pen.Brush.Cross 239 | ? pen.Brush.Cross 240 | : pen.Brush.Vertical; 241 | Image.SetPixel(x, y, symbol, pen.Color); 242 | } 243 | } 244 | } 245 | } -------------------------------------------------------------------------------- /src/ConsolePlot/Drawing/ConsoleImage.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace ConsolePlot.Drawing 4 | { 5 | /// 6 | /// Represents an image that can be drawn on the console. 7 | /// 8 | public class ConsoleImage 9 | { 10 | private readonly Pixel[,] _buffer; 11 | 12 | /// 13 | /// Gets the width of the image. 14 | /// 15 | public int Width { get; } 16 | 17 | /// 18 | /// Gets the height of the image. 19 | /// 20 | public int Height { get; } 21 | 22 | /// 23 | /// Initializes a new instance of the class with the specified width and height. 24 | /// 25 | /// The width of the image. 26 | /// The height of the image. 27 | public ConsoleImage(int width, int height) 28 | { 29 | Width = width; 30 | Height = height; 31 | _buffer = new Pixel[height, width]; 32 | } 33 | 34 | /// 35 | /// Sets a pixel at the specified coordinates. 36 | /// 37 | /// The x-coordinate of the pixel. 38 | /// The y-coordinate of the pixel. 39 | /// The character to set. 40 | /// The foreground color of the pixel. 41 | public void SetPixel(int x, int y, char c, ConsoleColor foregroundColor) 42 | { 43 | if (x >= 0 && x < Width && y >= 0 && y < Height) 44 | { 45 | _buffer[y, x] = new Pixel(c, foregroundColor); 46 | } 47 | } 48 | 49 | /// 50 | /// Gets the pixel at the specified coordinates. 51 | /// 52 | /// The x-coordinate of the pixel. 53 | /// The y-coordinate of the pixel. 54 | /// The pixel at the specified coordinates. 55 | /// Thrown when coordinates are out of bounds. 56 | public Pixel GetPixel(int x, int y) 57 | { 58 | if (x < 0 || x >= Width || y < 0 || y >= Height) 59 | { 60 | throw new ArgumentOutOfRangeException(nameof(x), "Coordinates are out of bounds."); 61 | } 62 | return _buffer[y, x]; 63 | } 64 | 65 | /// 66 | /// Renders the image to the console. 67 | /// 68 | public void Render() 69 | { 70 | for (int y = Height - 1; y >= 0; y--) 71 | { 72 | for (int x = 0; x < Width; x++) 73 | { 74 | var pixel = _buffer[y, x]; 75 | Console.ForegroundColor = pixel.ForegroundColor; 76 | Console.Write(pixel.Character); 77 | } 78 | Console.WriteLine(); 79 | } 80 | Console.ResetColor(); 81 | } 82 | } 83 | } -------------------------------------------------------------------------------- /src/ConsolePlot/Drawing/Pixel.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace ConsolePlot.Drawing 4 | { 5 | /// 6 | /// Represents a pixel in the console image. 7 | /// 8 | public readonly struct Pixel 9 | { 10 | /// 11 | /// Gets the character of the pixel. 12 | /// 13 | public char Character { get; } 14 | 15 | /// 16 | /// Gets the foreground color of the pixel. 17 | /// 18 | public ConsoleColor ForegroundColor { get; } 19 | 20 | /// 21 | /// Initializes a new instance of the struct. 22 | /// 23 | /// The character of the pixel. 24 | /// The foreground color of the pixel. 25 | public Pixel(char character, ConsoleColor foregroundColor) 26 | { 27 | Character = character; 28 | ForegroundColor = foregroundColor; 29 | } 30 | } 31 | } -------------------------------------------------------------------------------- /src/ConsolePlot/Drawing/Rectangle.cs: -------------------------------------------------------------------------------- 1 | namespace ConsolePlot.Drawing 2 | { 3 | /// 4 | /// Represents a rectangle with position and size. 5 | /// 6 | public readonly struct Rectangle 7 | { 8 | /// 9 | /// Gets the X-coordinate of the top-left corner of the rectangle. 10 | /// 11 | public int X { get; } 12 | 13 | /// 14 | /// Gets the Y-coordinate of the top-left corner of the rectangle. 15 | /// 16 | public int Y { get; } 17 | 18 | /// 19 | /// Gets the width of the rectangle. 20 | /// 21 | public int Width { get; } 22 | 23 | /// 24 | /// Gets the height of the rectangle. 25 | /// 26 | public int Height { get; } 27 | 28 | /// 29 | /// Gets the X-coordinate of the left edge of the rectangle. 30 | /// 31 | public int Left => X; 32 | 33 | /// 34 | /// Gets the Y-coordinate of the top edge of the rectangle. 35 | /// 36 | public int Top => Y + Height - 1; 37 | 38 | /// 39 | /// Gets the X-coordinate of the right edge of the rectangle. 40 | /// 41 | public int Right => X + Width - 1; 42 | 43 | /// 44 | /// Gets the Y-coordinate of the bottom edge of the rectangle. 45 | /// 46 | public int Bottom => Y; 47 | 48 | /// 49 | /// Initializes a new instance of the struct. 50 | /// 51 | /// The x-coordinate of the top-left corner. 52 | /// The y-coordinate of the top-left corner. 53 | /// The width of the rectangle. 54 | /// The height of the rectangle. 55 | public Rectangle(int x, int y, int width, int height) 56 | { 57 | X = x; 58 | Y = y; 59 | Width = width; 60 | Height = height; 61 | } 62 | 63 | /// 64 | /// Determines if the specified point defined by (x, y) coordinates is inside the rectangle. 65 | /// 66 | /// The x-coordinate of the point to test. 67 | /// The t-coordinate of the point to test. 68 | /// 69 | /// if the point is inside the rectangle; otherwise, . 70 | /// 71 | public bool Contains(int x, int y) 72 | { 73 | return ContainsX(x) && ContainsY(y); 74 | } 75 | 76 | /// 77 | /// Determines if the specified x-coordinate is within the horizontal bounds of the rectangle. 78 | /// 79 | /// The x-coordinate to test. 80 | /// 81 | /// if the x-coordinate is within the rectangle's horizontal bounds; otherwise, . 82 | /// 83 | public bool ContainsX(int x) 84 | { 85 | return x >= Left && x <= Right; 86 | } 87 | 88 | /// 89 | /// Determines if the specified y-coordinate is within the vertical bounds of the rectangle. 90 | /// 91 | /// The y-coordinate to test. 92 | /// 93 | /// if the y-coordinate is within the rectangle's vertical bounds; otherwise, . 94 | /// 95 | public bool ContainsY(int y) 96 | { 97 | return y >= Bottom && y <= Top; 98 | } 99 | } 100 | } -------------------------------------------------------------------------------- /src/ConsolePlot/Drawing/TextDirection.cs: -------------------------------------------------------------------------------- 1 | namespace ConsolePlot.Drawing 2 | { 3 | /// 4 | /// Specifies the direction of text rendering. 5 | /// 6 | public enum TextDirection 7 | { 8 | /// 9 | /// Text is rendered horizontally from left to right. 10 | /// 11 | Horizontal, 12 | 13 | /// 14 | /// Text is rendered vertically from top to bottom. 15 | /// 16 | Vertical 17 | } 18 | } -------------------------------------------------------------------------------- /src/ConsolePlot/Drawing/Tools/BrailleBrush.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace ConsolePlot.Drawing.Tools 4 | { 5 | /// 6 | /// Represents a brush that uses Braille characters to achieve higher resolution within a single console character. 7 | /// 8 | public class BrailleBrush : IPointBrush 9 | { 10 | private const char BrailleMinChar = '\u2800'; 11 | private const char BrailleMaxChar = '\u28FF'; 12 | 13 | /// 14 | public int HorizontalResolution => 2; 15 | 16 | /// 17 | public int VerticalResolution => 4; 18 | 19 | /// 20 | public char RenderPoint(char currentChar, int x, int y) 21 | { 22 | if (!IsBrailleCharacter(currentChar)) 23 | currentChar = BrailleMinChar; 24 | 25 | // Calculate the offset for the new dot 26 | int dotOffset = GetDotOffset(x, y); 27 | 28 | // Add the new dot to the existing character 29 | return (char)(currentChar | 1 << dotOffset); 30 | } 31 | 32 | private static bool IsBrailleCharacter(char c) => c >= BrailleMinChar && c <= BrailleMaxChar; 33 | 34 | private int GetDotOffset(int x, int y) 35 | { 36 | // Dot order in Braille characters: 37 | // 6 7 38 | // 2 5 39 | // 1 4 40 | // 0 3 41 | switch (x) 42 | { 43 | case 0: 44 | switch (y) 45 | { 46 | case 0: return 6; 47 | case 1: return 2; 48 | case 2: return 1; 49 | case 3: return 0; 50 | default: 51 | throw new ArgumentOutOfRangeException($"Invalid Braille cell coordinates: ({x}, {y})"); 52 | } 53 | case 1: 54 | switch (y) 55 | { 56 | case 0: return 7; 57 | case 1: return 5; 58 | case 2: return 4; 59 | case 3: return 3; 60 | default: 61 | throw new ArgumentOutOfRangeException($"Invalid Braille cell coordinates: ({x}, {y})"); 62 | } 63 | default: 64 | throw new ArgumentOutOfRangeException($"Invalid Braille cell coordinates: ({x}, {y})"); 65 | } 66 | } 67 | } 68 | } -------------------------------------------------------------------------------- /src/ConsolePlot/Drawing/Tools/ConsolePointBrush.cs: -------------------------------------------------------------------------------- 1 | namespace ConsolePlot.Drawing.Tools 2 | { 3 | /// 4 | /// Represents a brush for drawing points directly in the console with a 1x1 resolution, 5 | /// where each character cell represents a single point. 6 | /// This brush can be used in both and , 7 | /// but is optimized for console environments. 8 | /// 9 | public class ConsolePointBrush : IPointBrush 10 | { 11 | /// 12 | /// Gets the character used to draw points. 13 | /// 14 | public char PointChar { get; } 15 | 16 | /// 17 | /// Gets the horizontal resolution of the brush. 18 | /// 19 | public int HorizontalResolution => 1; 20 | 21 | /// 22 | /// Gets the vertical resolution of the brush. 23 | /// 24 | public int VerticalResolution => 1; 25 | 26 | /// 27 | /// Initializes a new instance of the class. 28 | /// 29 | /// The character to use for drawing points. 30 | public ConsolePointBrush(char pointChar) 31 | { 32 | PointChar = pointChar; 33 | } 34 | 35 | /// 36 | /// Renders a point using the brush. 37 | /// 38 | /// The current character at the drawing position. 39 | /// The x-coordinate within the character cell. 40 | /// The y-coordinate within the character cell. 41 | /// The new character to be drawn. 42 | public char RenderPoint(char currentChar, int x, int y) => PointChar; 43 | } 44 | } -------------------------------------------------------------------------------- /src/ConsolePlot/Drawing/Tools/ConsolePointPen.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace ConsolePlot.Drawing.Tools 4 | { 5 | /// 6 | /// Represents a pen for drawing points. 7 | /// 8 | public class ConsolePointPen 9 | { 10 | /// 11 | /// Gets the brush used by this pen. 12 | /// 13 | public ConsolePointBrush Brush { get; } 14 | 15 | /// 16 | /// Gets the color of this pen. 17 | /// 18 | public ConsoleColor Color { get; } 19 | 20 | /// 21 | /// Initializes a new instance of the class. 22 | /// 23 | /// The brush to use for drawing points. 24 | /// The color of the pen. 25 | public ConsolePointPen(ConsolePointBrush brush, ConsoleColor color) 26 | { 27 | Brush = brush; 28 | Color = color; 29 | } 30 | } 31 | } -------------------------------------------------------------------------------- /src/ConsolePlot/Drawing/Tools/IPointBrush.cs: -------------------------------------------------------------------------------- 1 | namespace ConsolePlot.Drawing.Tools 2 | { 3 | /// 4 | /// Defines the interface for a virtual brush used in high-resolution drawing operations, 5 | /// typically in environments where the drawing surface has a finer resolution than the console. 6 | /// Implementations of this interface can be used in but not in . 7 | /// 8 | public interface IPointBrush 9 | { 10 | /// 11 | /// Gets the horizontal resolution of the brush. 12 | /// 13 | int HorizontalResolution { get; } 14 | 15 | /// 16 | /// Gets the vertical resolution of the brush. 17 | /// 18 | int VerticalResolution { get; } 19 | 20 | /// 21 | /// Renders a point using the brush. 22 | /// 23 | /// The current character at the drawing position. 24 | /// The x-coordinate within the character cell. 25 | /// The y-coordinate within the character cell. 26 | /// The new character to be drawn. 27 | char RenderPoint(char currentChar, int x, int y); 28 | } 29 | } -------------------------------------------------------------------------------- /src/ConsolePlot/Drawing/Tools/LineBrush.cs: -------------------------------------------------------------------------------- 1 | namespace ConsolePlot.Drawing.Tools 2 | { 3 | /// 4 | /// Represents a brush for drawing lines with different styles for vertical, horizontal, and crossing lines. 5 | /// 6 | public class LineBrush 7 | { 8 | /// 9 | /// Gets the character used for vertical lines. 10 | /// 11 | public char Vertical { get; } 12 | 13 | /// 14 | /// Gets the character used for horizontal lines. 15 | /// 16 | public char Horizontal { get; } 17 | 18 | /// 19 | /// Gets the character used for line intersections. 20 | /// 21 | public char Cross { get; } 22 | 23 | /// 24 | /// Initializes a new instance of the class. 25 | /// 26 | /// The character for vertical lines. 27 | /// The character for horizontal lines. 28 | /// The character for line intersections. 29 | public LineBrush(char vertical, char horizontal, char cross) 30 | { 31 | Vertical = vertical; 32 | Horizontal = horizontal; 33 | Cross = cross; 34 | } 35 | } 36 | } -------------------------------------------------------------------------------- /src/ConsolePlot/Drawing/Tools/LinePen.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace ConsolePlot.Drawing.Tools 4 | { 5 | /// 6 | /// Represents a pen for drawing lines with a specific brush and color. 7 | /// 8 | public class LinePen 9 | { 10 | /// 11 | /// Gets the brush used by this pen. 12 | /// 13 | public LineBrush Brush { get; } 14 | 15 | /// 16 | /// Gets the color of this pen. 17 | /// 18 | public ConsoleColor Color { get; } 19 | 20 | /// 21 | /// Initializes a new instance of the class. 22 | /// 23 | /// The brush to use for drawing lines. 24 | /// The color of the pen. 25 | public LinePen(LineBrush brush, ConsoleColor color) 26 | { 27 | Brush = brush; 28 | Color = color; 29 | } 30 | } 31 | } -------------------------------------------------------------------------------- /src/ConsolePlot/Drawing/Tools/PointPen.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace ConsolePlot.Drawing.Tools 4 | { 5 | /// 6 | /// Represents a virtual pen for drawing operations. 7 | /// 8 | public class PointPen 9 | { 10 | /// 11 | /// Gets the brush used by this pen. 12 | /// 13 | public IPointBrush Brush { get; } 14 | 15 | /// 16 | /// Gets the color of this pen. 17 | /// 18 | public ConsoleColor Color { get; } 19 | 20 | /// 21 | /// Initializes a new instance of the class. 22 | /// 23 | /// The brush to use for drawing. 24 | /// The color of the pen. 25 | public PointPen(IPointBrush brush, ConsoleColor color) 26 | { 27 | Brush = brush; 28 | Color = color; 29 | } 30 | } 31 | } -------------------------------------------------------------------------------- /src/ConsolePlot/Drawing/Tools/QuadrantBrush.cs: -------------------------------------------------------------------------------- 1 | namespace ConsolePlot.Drawing.Tools 2 | { 3 | /// 4 | /// Represents a brush that uses quadrant characters for higher resolution drawing. 5 | /// 6 | public class QuadrantBrush : IPointBrush 7 | { 8 | private static readonly string QuadrantChars = " ▖▗▄▘▌▚▙▝▞▐▟▀▛▜█"; 9 | 10 | /// 11 | /// Gets the horizontal resolution of the brush. 12 | /// 13 | public int HorizontalResolution => 2; 14 | 15 | /// 16 | /// Gets the vertical resolution of the brush. 17 | /// 18 | public int VerticalResolution => 2; 19 | 20 | /// 21 | /// Renders a point using quadrant characters. 22 | /// 23 | /// The current character at the position. 24 | /// The x-coordinate within the character cell (0 or 1). 25 | /// The y-coordinate within the character cell (0 or 1). 26 | /// The new character representing the updated quadrant state. 27 | public char RenderPoint(char currentChar, int x, int y) 28 | { 29 | var index = QuadrantChars.IndexOf(currentChar); 30 | if (index == -1) 31 | { 32 | index = 0; 33 | } 34 | 35 | index |= 1 << (y * 2 + x); 36 | return QuadrantChars[index]; 37 | } 38 | } 39 | } -------------------------------------------------------------------------------- /src/ConsolePlot/Drawing/Tools/SystemLineBrushes.cs: -------------------------------------------------------------------------------- 1 | namespace ConsolePlot.Drawing.Tools 2 | { 3 | /// 4 | /// Provides a collection of predefined line brushes. 5 | /// 6 | public static class SystemLineBrushes 7 | { 8 | /// 9 | /// A brush for drawing thin lines. 10 | /// 11 | public static readonly LineBrush Thin = new LineBrush('│', '─', '┼'); 12 | 13 | /// 14 | /// A brush for drawing bold lines. 15 | /// 16 | public static readonly LineBrush Bold = new LineBrush('┃', '━', '╋'); 17 | 18 | /// 19 | /// A brush for drawing double lines. 20 | /// 21 | public static readonly LineBrush Double = new LineBrush('║', '═', '╬'); 22 | 23 | /// 24 | /// A brush for drawing dotted lines. 25 | /// 26 | public static readonly LineBrush Dotted = new LineBrush('┊', '╌', '┼'); 27 | 28 | /// 29 | /// A brush for drawing bold dotted lines. 30 | /// 31 | public static readonly LineBrush DottedBold = new LineBrush('┋', '╍', '╋'); 32 | 33 | /// 34 | /// A brush for drawing dashed lines. 35 | /// 36 | public static readonly LineBrush Dashed = new LineBrush('╎', '╴', '┤'); 37 | 38 | /// 39 | /// A brush for drawing bold dashed lines. 40 | /// 41 | public static readonly LineBrush DashedBold = new LineBrush('╏', '╸', '┫'); 42 | } 43 | 44 | } -------------------------------------------------------------------------------- /src/ConsolePlot/Drawing/Tools/SystemPointBrushes.cs: -------------------------------------------------------------------------------- 1 | namespace ConsolePlot.Drawing.Tools 2 | { 3 | /// 4 | /// Provides a collection of predefined point brushes. 5 | /// 6 | public static class SystemPointBrushes 7 | { 8 | /// 9 | /// A brush for drawing Braille points. 10 | /// 11 | public static readonly IPointBrush Braille = new BrailleBrush(); 12 | 13 | /// 14 | /// A brush for drawing quadrant points. 15 | /// 16 | public static readonly IPointBrush Quadrant = new QuadrantBrush(); 17 | 18 | /// 19 | /// A brush for drawing block characters. 20 | /// 21 | public static readonly ConsolePointBrush Block = new ConsolePointBrush('█'); 22 | 23 | /// 24 | /// A brush for drawing star characters. 25 | /// 26 | public static readonly ConsolePointBrush Star = new ConsolePointBrush('*'); 27 | 28 | /// 29 | /// A brush for drawing dot characters. 30 | /// 31 | public static readonly ConsolePointBrush Dot = new ConsolePointBrush('•'); 32 | } 33 | } -------------------------------------------------------------------------------- /src/ConsolePlot/Drawing/VirtualGraphics.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using ConsolePlot.Drawing.Tools; 3 | 4 | namespace ConsolePlot.Drawing 5 | { 6 | /// 7 | /// Represents a graphics context for drawing on a virtual image with higher resolution. 8 | /// 9 | public class VirtualGraphics : AbstractGraphics 10 | { 11 | private readonly PointPen _pen; 12 | 13 | /// 14 | /// Initializes a new instance of the class. 15 | /// 16 | /// The image to draw on. 17 | /// The virtual pen to use for drawing. 18 | public VirtualGraphics(ConsoleImage image, PointPen pen) 19 | : base( 20 | image, 21 | image.Width * pen.Brush.HorizontalResolution, 22 | image.Height * pen.Brush.VerticalResolution) 23 | { 24 | _pen = pen; 25 | } 26 | 27 | /// 28 | /// Draws a line connecting two points specified by the coordinate pairs. 29 | /// 30 | /// The x-coordinate of the first point. 31 | /// The y-coordinate of the first point. 32 | /// The x-coordinate of the second point. 33 | /// The y-coordinate of the second point. 34 | public void DrawLine(int x1, int y1, int x2, int y2) 35 | { 36 | DrawLineCore(_pen, x1, y1, x2, y2); 37 | } 38 | 39 | /// 40 | /// Draws a single point at the specified coordinates. 41 | /// 42 | /// The x-coordinate of the point. 43 | /// The y-coordinate of the point. 44 | public void DrawPoint(int x, int y) 45 | { 46 | DrawPointCore(_pen, x, y); 47 | } 48 | 49 | /// 50 | protected override void DrawPointCore(PointPen pen, int x, int y) 51 | { 52 | var bufferX = Math.DivRem(x, pen.Brush.HorizontalResolution, out var subX); 53 | var bufferY = Math.DivRem(y, pen.Brush.VerticalResolution, out var subY); 54 | 55 | if (ClipBounds.Contains(bufferX, bufferY)) 56 | { 57 | var pixel = Image.GetPixel(bufferX, bufferY); 58 | var oldChar = pixel.ForegroundColor == pen.Color ? pixel.Character : ' '; 59 | var newChar = pen.Brush.RenderPoint(oldChar, subX, subY); 60 | Image.SetPixel(bufferX, bufferY, newChar, pen.Color); 61 | } 62 | } 63 | } 64 | } -------------------------------------------------------------------------------- /src/ConsolePlot/Plot.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using ConsolePlot.Drawing; 5 | using ConsolePlot.Drawing.Tools; 6 | using ConsolePlot.Plotting; 7 | 8 | namespace ConsolePlot 9 | { 10 | /// 11 | /// Represents a plot that can be drawn on a console. 12 | /// 13 | public class Plot 14 | { 15 | private static readonly ConsoleColor[] AvailableColors = 16 | { 17 | ConsoleColor.Blue, 18 | ConsoleColor.Green, 19 | ConsoleColor.Cyan, 20 | ConsoleColor.Red, 21 | ConsoleColor.Magenta, 22 | ConsoleColor.Yellow, 23 | ConsoleColor.DarkBlue, 24 | ConsoleColor.DarkGreen, 25 | ConsoleColor.DarkCyan, 26 | ConsoleColor.DarkRed, 27 | ConsoleColor.DarkMagenta, 28 | ConsoleColor.DarkYellow 29 | }; 30 | private readonly ConsoleImage _image; 31 | private readonly PlotSettings _settings; 32 | 33 | /// 34 | /// Gets the axis settings for the plot. 35 | /// 36 | public AxisSettings Axis => _settings.Axis; 37 | 38 | /// 39 | /// Gets the grid settings for the plot. 40 | /// 41 | public GridSettings Grid => _settings.Grid; 42 | 43 | /// 44 | /// Gets the tick settings for the plot. 45 | /// 46 | public TickSettings Ticks => _settings.Ticks; 47 | 48 | /// 49 | /// Gets the collection of data series added to the plot. 50 | /// 51 | public List Series { get; } = new List(); 52 | 53 | /// 54 | /// Initializes a new instance of the class. 55 | /// 56 | /// The width of the plot in console characters. 57 | /// The height of the plot in console characters. 58 | /// Thrown when width or height is not positive. 59 | public Plot(int width, int height) 60 | { 61 | if (width <= 0 || height <= 0) 62 | { 63 | throw new ArgumentException("Width and height must be positive."); 64 | } 65 | 66 | _image = new ConsoleImage(width, height); 67 | _settings = new PlotSettings(); 68 | } 69 | 70 | /// 71 | /// Adds a new series to the plot. 72 | /// 73 | /// The X values of the series. 74 | /// The Y values of the series. 75 | /// The pen to use for drawing the series (optional). 76 | /// The instance for method chaining. 77 | /// Thrown when xs and ys have different lengths. 78 | public Series AddSeries( 79 | IReadOnlyCollection xs, 80 | IReadOnlyCollection ys, 81 | PointPen pen = null) 82 | { 83 | if (xs.Count != ys.Count) 84 | { 85 | throw new ArgumentException("X and Y collections must have the same length."); 86 | } 87 | 88 | if (pen == null) 89 | pen = new PointPen(_settings.DefaultGraphBrush ?? SystemPointBrushes.Braille, GetNextAvailableColor()); 90 | 91 | var series = new Series(xs, ys, pen); 92 | Series.Add(new Series(xs, ys, pen)); 93 | return series; 94 | } 95 | 96 | /// 97 | /// Draws the plot on the console image. 98 | /// 99 | public void Draw() 100 | { 101 | _settings.Validate(); 102 | var plotData = PlotData.Calculate(Series, _settings, _image.Width, _image.Height); 103 | var renderer = new PlotRenderer(_image, plotData, _settings); 104 | 105 | renderer.Draw(); 106 | } 107 | 108 | /// 109 | /// Gets the underlying . 110 | /// 111 | /// The this plotting context is drawing on. 112 | public ConsoleImage GetImage() => _image; 113 | 114 | /// 115 | /// Renders the plot on the console. 116 | /// 117 | public void Render() => _image.Render(); 118 | 119 | private ConsoleColor GetNextAvailableColor() 120 | { 121 | var usedColors = new HashSet(); 122 | 123 | // Include colors of existing series 124 | usedColors.UnionWith(Series.Select(s => s.Pen.Color)); 125 | 126 | // Include axis color if visible 127 | if (_settings.Axis.IsVisible) 128 | { 129 | usedColors.Add(_settings.Axis.Pen.Color); 130 | } 131 | 132 | // Include grid color if visible 133 | if (_settings.Grid.IsVisible) 134 | { 135 | usedColors.Add(_settings.Grid.Pen.Color); 136 | } 137 | 138 | // Return the first available color 139 | return AvailableColors.First(c => !usedColors.Contains(c)); 140 | } 141 | } 142 | } -------------------------------------------------------------------------------- /src/ConsolePlot/Plotting/AxisSettings.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using ConsolePlot.Drawing.Tools; 3 | 4 | namespace ConsolePlot.Plotting 5 | { 6 | /// 7 | /// Represents the axis settings for the plot. 8 | /// 9 | public class AxisSettings 10 | { 11 | /// 12 | /// Gets or sets a value indicating whether the axis is visible. 13 | /// 14 | public bool IsVisible { get; set; } = true; 15 | 16 | /// 17 | /// Gets or sets the pen used to draw the axis. 18 | /// 19 | public LinePen Pen { get; set; } = new LinePen(SystemLineBrushes.Thin, ConsoleColor.White); 20 | 21 | /// 22 | /// Validates the axis settings. 23 | /// 24 | /// Thrown when the pen is null. 25 | public void Validate() 26 | { 27 | if (Pen == null) 28 | throw new InvalidOperationException("Axis pen cannot be null."); 29 | } 30 | } 31 | } -------------------------------------------------------------------------------- /src/ConsolePlot/Plotting/Bounds.cs: -------------------------------------------------------------------------------- 1 | namespace ConsolePlot.Plotting 2 | { 3 | internal class Bounds 4 | { 5 | public double XMin { get; } 6 | public double XMax { get; } 7 | public double YMin { get; } 8 | public double YMax { get; } 9 | 10 | public Bounds(double xMin, double xMax, double yMin, double yMax) 11 | { 12 | XMin = xMin; 13 | XMax = xMax; 14 | YMin = yMin; 15 | YMax = yMax; 16 | } 17 | } 18 | } -------------------------------------------------------------------------------- /src/ConsolePlot/Plotting/CoordinateConverter.cs: -------------------------------------------------------------------------------- 1 | namespace ConsolePlot.Plotting 2 | { 3 | /// 4 | /// Converts coordinates between different coordinate systems. 5 | /// 6 | internal class CoordinateConverter 7 | { 8 | public (double Min, double Max) SourceX { get; } 9 | public (double Min, double Max) SourceY { get; } 10 | public (int Min, int Max) TargetX { get; } 11 | public (int Min, int Max) TargetY { get; } 12 | 13 | public CoordinateConverter( 14 | double sourceXMin, double sourceXMax, int targetXMin, int targetXMax, 15 | double sourceYMin, double sourceYMax, int targetYMin, int targetYMax) 16 | { 17 | SourceX = (sourceXMin, sourceXMax); 18 | SourceY = (sourceYMin, sourceYMax); 19 | TargetX = (targetXMin, targetXMax); 20 | TargetY = (targetYMin, targetYMax); 21 | } 22 | 23 | public double ConvertX(double value) => 24 | ConvertValue(value, SourceX.Min, SourceX.Max, TargetX.Min, TargetX.Max); 25 | 26 | public double ConvertY(double value) => 27 | ConvertValue(value, SourceY.Min, SourceY.Max, TargetY.Min, TargetY.Max); 28 | 29 | public (double X, double Y) Convert(double x, double y) => (ConvertX(x), ConvertY(y)); 30 | 31 | private static double ConvertValue(double value, double sourceMin, double sourceMax, int targetMin, int targetMax) => 32 | (value - sourceMin) / (sourceMax - sourceMin) * (targetMax - targetMin) + targetMin; 33 | } 34 | } -------------------------------------------------------------------------------- /src/ConsolePlot/Plotting/GraphGraphics.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using ConsolePlot.Drawing; 4 | using ConsolePlot.Drawing.Tools; 5 | 6 | namespace ConsolePlot.Plotting 7 | { 8 | /// 9 | /// Provides drawing capabilities for graphs using double-precision coordinates. 10 | /// 11 | internal class GraphGraphics 12 | { 13 | private readonly ConsoleGraphics _graphics; 14 | private readonly CoordinateConverter _converter; 15 | 16 | public GraphGraphics(ConsoleGraphics graphics, CoordinateConverter converter) 17 | { 18 | _graphics = graphics; 19 | _converter = converter; 20 | } 21 | 22 | public void DrawLines(PointPen pen, IReadOnlyList xs, IReadOnlyList ys) 23 | { 24 | var graphics = new VirtualGraphics(_graphics.GetImage(), pen); 25 | var converter = new CoordinateConverter( 26 | _converter.SourceX.Min, 27 | _converter.SourceX.Max, 28 | _converter.TargetX.Min * pen.Brush.HorizontalResolution, 29 | _converter.TargetX.Max * pen.Brush.HorizontalResolution, 30 | _converter.SourceY.Min, 31 | _converter.SourceY.Max, 32 | _converter.TargetY.Min * pen.Brush.VerticalResolution, 33 | _converter.TargetY.Max * pen.Brush.VerticalResolution); 34 | 35 | int? x1 = null, y1 = null; 36 | 37 | for (int i = 0; i < xs.Count; i++) 38 | { 39 | var (x2, y2) = Convert(xs[i], ys[i]); 40 | 41 | if (x1 != null && y1 != null && x2 != null && y2 != null) 42 | graphics.DrawLine(x1.Value, y1.Value, x2.Value, y2.Value); 43 | 44 | x1 = x2; 45 | y1 = y2; 46 | } 47 | 48 | (int?, int?) Convert(double x, double y) 49 | { 50 | if (double.IsNaN(x) || double.IsNaN(y)) return (null, null); 51 | 52 | return (ConvertInfinity(x) ?? (int)Math.Round(converter.ConvertX(x)), 53 | ConvertInfinity(y) ?? (int)Math.Round(converter.ConvertY(y))); 54 | } 55 | 56 | int? ConvertInfinity(double value) 57 | { 58 | if (double.IsPositiveInfinity(value)) return int.MaxValue; 59 | if (double.IsNegativeInfinity(value)) return int.MinValue; 60 | return null; 61 | } 62 | } 63 | 64 | public void DrawVertical(LinePen pen, double x) => 65 | _graphics.DrawVertical(pen, ConvertX(x)); 66 | 67 | public void DrawVertical(LinePen pen, double x, double y) => 68 | _graphics.DrawVertical(pen, ConvertX(x), ConvertY(y)); 69 | 70 | public void DrawHorizontal(LinePen pen, double y) => 71 | _graphics.DrawHorizontal(pen, ConvertY(y)); 72 | 73 | public void DrawHorizontal(LinePen pen, double x, double y) => 74 | _graphics.DrawHorizontal(pen, ConvertX(x), ConvertY(y)); 75 | 76 | private int ConvertX(double x) => (int)Math.Round(_converter.ConvertX(x)); 77 | private int ConvertY(double y) => (int)Math.Round(_converter.ConvertY(y)); 78 | } 79 | } -------------------------------------------------------------------------------- /src/ConsolePlot/Plotting/GridSettings.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using ConsolePlot.Drawing.Tools; 3 | 4 | namespace ConsolePlot.Plotting 5 | { 6 | /// 7 | /// Represents the grid settings for the plot. 8 | /// 9 | public class GridSettings 10 | { 11 | /// 12 | /// Gets or sets a value indicating whether the grid is visible. 13 | /// 14 | public bool IsVisible { get; set; } = true; 15 | 16 | /// 17 | /// Gets or sets the pen used to draw the grid. 18 | /// 19 | public LinePen Pen { get; set; } = new LinePen(SystemLineBrushes.Dashed, ConsoleColor.DarkGray); 20 | 21 | /// 22 | /// Validates the grid settings. 23 | /// 24 | /// Thrown when the pen is null. 25 | public void Validate() 26 | { 27 | if (Pen == null) 28 | throw new InvalidOperationException("Grid pen cannot be null."); 29 | } 30 | } 31 | } -------------------------------------------------------------------------------- /src/ConsolePlot/Plotting/LabelSettings.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace ConsolePlot.Plotting 4 | { 5 | /// 6 | /// Represents the label settings for tick marks. 7 | /// 8 | public class LabelSettings 9 | { 10 | /// 11 | /// Gets or sets a value indicating whether tick labels are visible. 12 | /// 13 | public bool IsVisible { get; set; } = true; 14 | 15 | /// 16 | /// Gets or sets the color of the tick labels. 17 | /// 18 | public ConsoleColor Color { get; set; } = ConsoleColor.White; 19 | 20 | /// 21 | /// Gets or sets a value indicating whether labels should be attached to the axis. 22 | /// 23 | public bool AttachToAxis { get; set; } = true; 24 | 25 | /// 26 | /// Gets or sets the string format used to format tick labels. 27 | /// 28 | public string Format { get; set; } = "G4"; 29 | 30 | /// 31 | /// Validates the labels settings. 32 | /// 33 | public void Validate() 34 | { 35 | // No validation needed for current properties 36 | } 37 | } 38 | } -------------------------------------------------------------------------------- /src/ConsolePlot/Plotting/PlotData.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using ConsolePlot.Drawing; 5 | 6 | namespace ConsolePlot.Plotting 7 | { 8 | /// 9 | /// Represents the calculated data for plotting. 10 | /// 11 | internal class PlotData 12 | { 13 | /// 14 | /// Gets the axis intersection point. 15 | /// 16 | public Point Axis { get; } 17 | 18 | /// 19 | /// Gets the data bounds of the plot. 20 | /// 21 | public Bounds DataBounds { get; } 22 | 23 | /// 24 | /// Gets the drawing area of the plot. 25 | /// 26 | public Rectangle DrawingArea { get; } 27 | 28 | /// 29 | /// Gets the series to be plotted. 30 | /// 31 | public List Series { get; } 32 | 33 | /// 34 | /// Gets the X-axis ticks. 35 | /// 36 | public List XTicks { get; } 37 | 38 | /// 39 | /// Gets the Y-axis ticks. 40 | /// 41 | public List YTicks { get; } 42 | 43 | private PlotData( 44 | Bounds dataBounds, 45 | Rectangle drawingArea, 46 | List xTicks, 47 | List yTicks, 48 | Point axis, 49 | List series) 50 | { 51 | DataBounds = dataBounds; 52 | DrawingArea = drawingArea; 53 | XTicks = xTicks; 54 | YTicks = yTicks; 55 | Axis = axis; 56 | Series = series; 57 | } 58 | 59 | /// 60 | /// Calculates the plot data based on the provided series and settings. 61 | /// 62 | public static PlotData Calculate(List series, PlotSettings settings, int width, int height) 63 | { 64 | var initialBounds = CalculateDataBounds(series); 65 | 66 | // Check for the special case where all visual elements are disabled 67 | if (!settings.Ticks.Labels.IsVisible && 68 | !settings.Ticks.IsVisible && 69 | !settings.Axis.IsVisible && 70 | !settings.Grid.IsVisible) 71 | { 72 | return new PlotData(initialBounds, new Rectangle(0, 0, width, height), new List(), new List(), new Point(0, 0), series); 73 | } 74 | 75 | var (adjustedYBounds, yTicks) = CalculateAdjustedBoundsAndTicks(settings, initialBounds.YMin, 76 | initialBounds.YMax, settings.Ticks.DesiredYStep, height, CalculateXTickLabelSize()); 77 | var (adjustedXBounds, xTicks) = CalculateAdjustedBoundsAndTicks(settings, initialBounds.XMin, 78 | initialBounds.XMax, settings.Ticks.DesiredXStep, width, CalculateYTickLabelSize(yTicks)); 79 | 80 | var adjustedBounds = new Bounds(adjustedXBounds.min, adjustedXBounds.max, adjustedYBounds.min, 81 | adjustedYBounds.max); 82 | var axisCross = CalculateAxisCross(xTicks, yTicks); 83 | var drawingArea = CalculateDrawingArea(settings, CalculateXTickLabelSize(), CalculateYTickLabelSize(yTicks), 84 | width, height); 85 | 86 | return new PlotData(adjustedBounds, drawingArea, xTicks, yTicks, axisCross, series); 87 | } 88 | 89 | private static ((double min, double max) bounds, List ticks) CalculateAdjustedBoundsAndTicks( 90 | PlotSettings settings, 91 | double min, 92 | double max, 93 | int desiredStepSize, 94 | int size, 95 | int labelSize) 96 | { 97 | var tickStep = CalculateTickStep(min, max, desiredStepSize, size); 98 | var ticks = GenerateTicks(min, max, tickStep, settings.Ticks.Labels.Format, false); 99 | 100 | var drawingRange = CalculateDrawingRange(settings, labelSize, size); 101 | 102 | // Adjust the data bounds so that the ticks match the cells 103 | var (adjustedMin, adjustedMax) = AdjustDataBoundsToTicks(settings, min, max, ticks, drawingRange, labelSize); 104 | // The new bounds will be wider, so we need to generate new ticks. 105 | ticks = GenerateTicks(adjustedMin, adjustedMax, tickStep, settings.Ticks.Labels.Format, true); 106 | 107 | return ((adjustedMin, adjustedMax), ticks); 108 | } 109 | 110 | private static int CalculateXTickLabelSize() 111 | { 112 | return 1; 113 | } 114 | 115 | private static int CalculateYTickLabelSize(List yTicks) 116 | { 117 | return yTicks.Max(t => t.Label.Length); 118 | } 119 | 120 | private static Bounds CalculateDataBounds(List series) 121 | { 122 | var xValues = series.SelectMany(s => s.Xs).Where(d => !double.IsInfinity(d) && !double.IsNaN(d)); 123 | var yValues = series.SelectMany(s => s.Ys).Where(d => !double.IsInfinity(d) && !double.IsNaN(d)); 124 | 125 | return new Bounds(xValues.Min(), xValues.Max(), yValues.Min(), yValues.Max()); 126 | } 127 | 128 | private static double CalculateTickStep(double min, double max, int desiredStep, int size) 129 | { 130 | return NiceNumber((max - min) / (size / desiredStep), true); 131 | } 132 | 133 | private static List GenerateTicks( 134 | double min, 135 | double max, 136 | double stepSize, 137 | string format, 138 | bool fitWithinBounds) 139 | { 140 | var minStep = (int)(fitWithinBounds ? Math.Ceiling(min / stepSize) : Math.Round(min / stepSize)); 141 | var maxStep = (int)(fitWithinBounds ? Math.Floor(max / stepSize) : Math.Round(max / stepSize)); 142 | 143 | return Enumerable.Range(minStep, maxStep - minStep + 1) 144 | .Select(step => 145 | { 146 | var tickValue = step * stepSize; 147 | return new Tick(tickValue, tickValue.ToString(format)); 148 | }) 149 | .ToList(); 150 | } 151 | 152 | private static double NiceNumber(double range, bool round) 153 | { 154 | var exponent = Math.Floor(Math.Log10(range)); 155 | var fraction = range / Math.Pow(10, exponent); 156 | 157 | double niceFraction; 158 | 159 | if (round) 160 | { 161 | if (fraction < 1.5) 162 | niceFraction = 1; 163 | else if (fraction < 3) 164 | niceFraction = 2; 165 | else if (fraction < 7) 166 | niceFraction = 5; 167 | else 168 | niceFraction = 10; 169 | } 170 | else 171 | { 172 | if (fraction <= 1) 173 | niceFraction = 1; 174 | else if (fraction <= 2) 175 | niceFraction = 2; 176 | else if (fraction <= 5) 177 | niceFraction = 5; 178 | else 179 | niceFraction = 10; 180 | } 181 | 182 | return niceFraction * Math.Pow(10, exponent); 183 | } 184 | 185 | /// 186 | /// Adjusts the bounds of a graph to fit within a specified number of console characters. 187 | /// 188 | /// List of ticks to be displayed on the axis. 189 | /// Plot settings 190 | /// Initial minimum value of the data range. 191 | /// Initial maximum value of the data range. 192 | /// Total number of console characters available for the graph. 193 | /// Width of the axis label in characters. 194 | /// A tuple containing the adjusted minimum and maximum values for the graph. 195 | /// 196 | /// This method ensures that: 197 | /// 198 | /// All ticks and data points fit within the specified number of characters. 199 | /// The axis label (placed to the left of the first tick) doesn't overflow. 200 | /// Ticks align with character positions. 201 | /// The graph is centered if there's extra space. 202 | /// 203 | /// The method calculates the optimal character size and adjusts the value range accordingly. 204 | /// 205 | private static (double min, double max) AdjustDataBoundsToTicks( 206 | PlotSettings settings, 207 | double initialMinValue, 208 | double initialMaxValue, 209 | List ticks, 210 | int totalCharacters, 211 | int axisLabelWidth) 212 | { 213 | // Find the range of values 214 | var minTickValue = ticks.First().Value; 215 | var maxTickValue = ticks.Last().Value; 216 | var minValue = Math.Min(initialMinValue, minTickValue); 217 | var maxValue = Math.Max(initialMaxValue, maxTickValue); 218 | 219 | var cross = CalculateAxisCross(ticks); 220 | 221 | // Calculate character size hypotheses 222 | var characterSizeByFullRange = (maxValue - minValue) / (totalCharacters - 1); 223 | 224 | // Is the data range starts with the label attached to the axis? 225 | bool isLabelAtStart; 226 | double minCharacterSize; 227 | 228 | if (settings.Ticks.Labels.IsVisible && settings.Ticks.Labels.AttachToAxis) 229 | { 230 | // Choose the larger character size 231 | var characterSizeWithLabelAtStart = (maxValue - cross) / (totalCharacters - 1 - axisLabelWidth); 232 | isLabelAtStart = characterSizeWithLabelAtStart > characterSizeByFullRange; 233 | minCharacterSize = isLabelAtStart ? characterSizeWithLabelAtStart : characterSizeByFullRange; 234 | } 235 | else 236 | { 237 | isLabelAtStart = false; 238 | minCharacterSize = characterSizeByFullRange; 239 | } 240 | 241 | // Adjust character size based on tick intervals 242 | var tickInterval = (maxTickValue - minTickValue) / (ticks.Count - 1); 243 | var charactersPerTick = (int)Math.Floor(tickInterval / minCharacterSize); 244 | var adjustedCharacterSize = tickInterval / charactersPerTick; 245 | 246 | // Calculate the value of the first character 247 | var firstCharacterValue = isLabelAtStart 248 | ? minTickValue - axisLabelWidth * adjustedCharacterSize 249 | : minTickValue - Math.Ceiling((minTickValue - initialMinValue) / adjustedCharacterSize) * 250 | adjustedCharacterSize; 251 | 252 | // Center the content if there's extra space 253 | var usedCharacters = (int)Math.Ceiling((initialMaxValue - firstCharacterValue) / adjustedCharacterSize); 254 | var unusedCharacters = (totalCharacters - usedCharacters) / 2; 255 | firstCharacterValue -= unusedCharacters * adjustedCharacterSize; 256 | 257 | // Calculate the value of the last character 258 | var lastCharacterValue = firstCharacterValue + (totalCharacters - 1) * adjustedCharacterSize; 259 | 260 | return (firstCharacterValue, lastCharacterValue); 261 | } 262 | 263 | private static Point CalculateAxisCross(List xTicks, List yTicks) 264 | { 265 | return new Point(CalculateAxisCross(xTicks), CalculateAxisCross(yTicks)); 266 | } 267 | 268 | private static double CalculateAxisCross(List ticks) 269 | { 270 | return ticks.Min(t => Math.Abs(t.Value)); 271 | } 272 | 273 | private static Rectangle CalculateDrawingArea( 274 | PlotSettings settings, 275 | int xLabelSize, 276 | int yLabelSize, 277 | int width, 278 | int height) 279 | { 280 | var drawingAreaX = CalculateDrawingRange(settings, yLabelSize, width); 281 | var drawingAreaY = CalculateDrawingRange(settings, xLabelSize, height); 282 | 283 | return new Rectangle(width - drawingAreaX, height - drawingAreaY, drawingAreaX, drawingAreaY); 284 | } 285 | 286 | private static int CalculateDrawingRange(PlotSettings settings, int labelSize, int size) 287 | { 288 | return settings.Ticks.Labels.IsVisible && !settings.Ticks.Labels.AttachToAxis 289 | ? size - labelSize 290 | : size; 291 | } 292 | } 293 | } -------------------------------------------------------------------------------- /src/ConsolePlot/Plotting/PlotRenderer.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Linq; 3 | using ConsolePlot.Drawing; 4 | 5 | namespace ConsolePlot.Plotting 6 | { 7 | /// 8 | /// Renders the plot data onto a console image. 9 | /// 10 | internal class PlotRenderer 11 | { 12 | private readonly ConsoleImage _image; 13 | private readonly PlotData _plotData; 14 | private readonly PlotSettings _settings; 15 | 16 | /// 17 | /// Initializes a new instance of the PlotRenderer class. 18 | /// 19 | public PlotRenderer(ConsoleImage image, PlotData plotData, PlotSettings settings) 20 | { 21 | _image = image; 22 | _plotData = plotData; 23 | _settings = settings; 24 | } 25 | 26 | /// 27 | /// Draws the plot on the console image. 28 | /// 29 | public void Draw() 30 | { 31 | var graphics = new ConsoleGraphics(_image); 32 | var converter = CreateConverter(_plotData.DataBounds, _plotData.DrawingArea); 33 | var graphGraphics = new GraphGraphics(graphics, converter); 34 | 35 | graphics.Clear(); 36 | 37 | graphics.SetClip(_plotData.DrawingArea); 38 | 39 | if (_settings.Grid.IsVisible) 40 | DrawGrid(graphGraphics); 41 | 42 | if (_settings.Axis.IsVisible) 43 | DrawAxes(graphGraphics); 44 | 45 | if (_settings.Ticks.IsVisible) 46 | DrawTicks(graphGraphics); 47 | 48 | graphics.ResetClip(); 49 | 50 | DrawSeries(graphGraphics); 51 | 52 | if (_settings.Ticks.Labels.IsVisible) 53 | DrawLabels(graphics, converter); 54 | } 55 | 56 | private void DrawGrid(GraphGraphics graphics) 57 | { 58 | foreach (var tick in _plotData.XTicks) 59 | graphics.DrawVertical(_settings.Grid.Pen, tick.Value); 60 | foreach (var tick in _plotData.YTicks) 61 | graphics.DrawHorizontal(_settings.Grid.Pen, tick.Value); 62 | } 63 | 64 | private void DrawAxes(GraphGraphics graphics) 65 | { 66 | graphics.DrawHorizontal(_settings.Axis.Pen, _plotData.Axis.Y); 67 | graphics.DrawVertical(_settings.Axis.Pen, _plotData.Axis.X); 68 | } 69 | 70 | private void DrawTicks(GraphGraphics graphics) 71 | { 72 | foreach (var tick in _plotData.XTicks) 73 | graphics.DrawVertical(_settings.Ticks.Pen, tick.Value, _plotData.Axis.Y); 74 | foreach (var tick in _plotData.YTicks) 75 | graphics.DrawHorizontal(_settings.Ticks.Pen, _plotData.Axis.X, tick.Value); 76 | } 77 | 78 | private void DrawSeries(GraphGraphics graphics) 79 | { 80 | foreach (var series in _plotData.Series) 81 | { 82 | graphics.DrawLines(series.Pen, series.Xs, series.Ys); 83 | } 84 | } 85 | 86 | private void DrawLabels(ConsoleGraphics graphics, CoordinateConverter converter) 87 | { 88 | DrawXLabels(graphics, converter); 89 | DrawYLabels(graphics, converter); 90 | } 91 | 92 | private void DrawXLabels(ConsoleGraphics graphics, CoordinateConverter converter) 93 | { 94 | var y = _settings.Ticks.Labels.AttachToAxis 95 | ? (int)Math.Round(converter.ConvertY(_plotData.Axis.Y)) 96 | : 0; 97 | 98 | foreach (var tick in _plotData.XTicks) 99 | { 100 | var x = (int)Math.Round(converter.ConvertX(tick.Value)); 101 | if (!_settings.Ticks.Labels.AttachToAxis || tick.Value != _plotData.Axis.X) 102 | { 103 | graphics.DrawString(tick.Label, _settings.Ticks.Labels.Color, x - tick.Label.Length / 2, y - 1, ensureVisible: true); 104 | } 105 | } 106 | } 107 | 108 | private void DrawYLabels(ConsoleGraphics graphics, CoordinateConverter converter) 109 | { 110 | var x = _settings.Ticks.Labels.AttachToAxis 111 | ? (int)Math.Round(converter.ConvertX(_plotData.Axis.X)) 112 | : _plotData.YTicks.Select(t => t.Label.Length).Max(); 113 | 114 | foreach (var tick in _plotData.YTicks) 115 | { 116 | var y = (int)Math.Round(converter.ConvertY(tick.Value)); 117 | if (_settings.Ticks.Labels.AttachToAxis && tick.Value == _plotData.Axis.Y) 118 | { 119 | y -= 1; 120 | } 121 | graphics.DrawString(tick.Label, _settings.Ticks.Labels.Color, x - tick.Label.Length, y, ensureVisible: true); 122 | } 123 | } 124 | 125 | private CoordinateConverter CreateConverter(Bounds dataBounds, Rectangle drawingArea) 126 | { 127 | return new CoordinateConverter( 128 | dataBounds.XMin, dataBounds.XMax, drawingArea.Left, drawingArea.Right, 129 | dataBounds.YMin, dataBounds.YMax, drawingArea.Bottom, drawingArea.Top); 130 | } 131 | } 132 | } -------------------------------------------------------------------------------- /src/ConsolePlot/Plotting/PlotSettings.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using ConsolePlot.Drawing.Tools; 3 | 4 | namespace ConsolePlot.Plotting 5 | { 6 | /// 7 | /// Represents the overall plot settings. 8 | /// 9 | public class PlotSettings 10 | { 11 | /// 12 | /// Gets the axis settings for the plot. 13 | /// 14 | public AxisSettings Axis { get; } = new AxisSettings(); 15 | 16 | /// 17 | /// Gets the grid settings for the plot. 18 | /// 19 | public GridSettings Grid { get; } = new GridSettings(); 20 | 21 | /// 22 | /// Gets the tick settings for the plot. 23 | /// 24 | public TickSettings Ticks { get; } = new TickSettings(); 25 | 26 | /// 27 | /// Gets or sets the default brush used to draw series if none is provided. 28 | /// 29 | public IPointBrush DefaultGraphBrush { get; set; } = SystemPointBrushes.Braille; 30 | 31 | /// 32 | /// Validates all settings. 33 | /// 34 | /// Thrown when any setting is invalid. 35 | public void Validate() 36 | { 37 | Axis.Validate(); 38 | Grid.Validate(); 39 | Ticks.Validate(); 40 | } 41 | } 42 | } -------------------------------------------------------------------------------- /src/ConsolePlot/Plotting/Point.cs: -------------------------------------------------------------------------------- 1 | namespace ConsolePlot.Plotting 2 | { 3 | internal struct Point 4 | { 5 | public double X { get; } 6 | public double Y { get; } 7 | 8 | public Point(double x, double y) 9 | { 10 | X = x; 11 | Y = y; 12 | } 13 | } 14 | } -------------------------------------------------------------------------------- /src/ConsolePlot/Plotting/Series.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using ConsolePlot.Drawing.Tools; 5 | 6 | namespace ConsolePlot.Plotting 7 | { 8 | /// 9 | /// Represents a series of data points in a plot. 10 | /// 11 | public class Series 12 | { 13 | /// 14 | /// Gets the X values of the series. 15 | /// 16 | public IReadOnlyList Xs { get; } 17 | 18 | /// 19 | /// Gets the Y values of the series. 20 | /// 21 | public IReadOnlyList Ys { get; } 22 | 23 | /// 24 | /// Gets the pen used to draw the series. 25 | /// 26 | public PointPen Pen { get; } 27 | 28 | /// 29 | /// Initializes a new instance of the class. 30 | /// 31 | /// The X values of the series. 32 | /// The Y values of the series. 33 | /// The pen to use for drawing the series. 34 | /// Thrown when xs and ys have different lengths or when pen is null. 35 | public Series(IEnumerable xs, IEnumerable ys, PointPen pen) 36 | { 37 | Xs = xs.ToList(); 38 | Ys = ys.ToList(); 39 | 40 | if (Xs.Count != Ys.Count) 41 | throw new ArgumentException("X and Y collections must have the same length."); 42 | 43 | Pen = pen ?? throw new ArgumentNullException(nameof(pen)); 44 | } 45 | } 46 | } -------------------------------------------------------------------------------- /src/ConsolePlot/Plotting/Tick.cs: -------------------------------------------------------------------------------- 1 | namespace ConsolePlot.Plotting 2 | { 3 | internal class Tick 4 | { 5 | public double Value { get; } 6 | public string Label { get; } 7 | 8 | public Tick(double value, string label) 9 | { 10 | Value = value; 11 | Label = label; 12 | } 13 | } 14 | } -------------------------------------------------------------------------------- /src/ConsolePlot/Plotting/TickSettings.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using ConsolePlot.Drawing.Tools; 3 | 4 | namespace ConsolePlot.Plotting 5 | { 6 | /// 7 | /// Represents the tick settings for the plot axes. 8 | /// 9 | public class TickSettings 10 | { 11 | /// 12 | /// Gets or sets a value indicating whether ticks are visible. 13 | /// 14 | public bool IsVisible { get; set; } = true; 15 | 16 | /// 17 | /// Gets or sets the pen used to draw the ticks. 18 | /// 19 | public LinePen Pen { get; set; } = new LinePen(SystemLineBrushes.Thin, ConsoleColor.White); 20 | 21 | /// 22 | /// Gets or sets the desired step between ticks on the horizontal axis. 23 | /// 24 | public int DesiredXStep { get; set; } = 11; 25 | 26 | /// 27 | /// Gets or sets the desired step between ticks on the vertical axis. 28 | /// 29 | public int DesiredYStep { get; set; } = 3; 30 | 31 | /// 32 | /// Gets the label settings associated with the ticks. 33 | /// 34 | public LabelSettings Labels { get; } = new LabelSettings(); 35 | 36 | /// 37 | /// Validates the tick settings. 38 | /// 39 | public void Validate() 40 | { 41 | Labels.Validate(); 42 | } 43 | } 44 | } --------------------------------------------------------------------------------