푸터 콘텐츠로 바로가기
.NET 도움말

NPlot C# (How It Works For Developers)

This tutorial is designed for beginners who are keen to explore the integration of two powerful libraries: NPlot and IronPDF. Together, they form a robust toolkit for creating and exporting charts in C# applications.

NPlot is a versatile charting library in the .NET framework, ideal for generating a wide range of graphs and plots. From simple line plots to complex scatter charts, NPlot excels in displaying sample-based data and generating dynamic charts, whether you're working with small datasets or very large datasets.

IronPDF complements NPlot by enabling the conversion of these charts into PDF documents. Whether you're dealing with HTML email content or specific plot classes, IronPDF can render them into high-quality PDFs.

This functionality is particularly useful for applications that require report generation or documentation of analyzed data.

Getting Started with NPlot

Introduction to NPlot in the .NET Framework

NPlot is a dynamic charting library designed for the .NET Framework, catering to a broad range of data visualization needs. Whether you're working on desktop applications or web-based solutions, NPlot offers the functionality to represent data graphically, clearly, and effectively.

Installing NPlot in Your C# Project

To begin using NPlot in your C# project, you need to install it. Here's how you can easily add NPlot to your application:

Using NuGet Package Manager:

  1. In Visual Studio, go to 'Tools' > 'NuGet Package Manager' > 'Manage NuGet Packages for Solution...'.
  2. Search for 'NPlot' and install it in your project.

NPlot C# (How It Works For Developers): Figure 1

First Steps with NPlot

Once NPlot is installed, you can start creating charts. NPlot's ease of use makes it ideal for beginners, allowing for the creation of plots with just a few lines of code.

Creating a Basic Chart

Let's create a simple line plot as our first chart:

Setting Up the Plot Surface: Create a PlotSurface2D object. This acts as the canvas for your plot. Set a few display properties to customize its appearance, such as the background color and title.

Adding Data to the Plot: Use NPlot's LinePlot class to create a line plot. Add data values belonging to one or more categories. These data points will be plotted on the graph.

Displaying the Chart: Add the line plot to the plot surface. Render the plot surface in a form or a user control for display.

using System;
using NPlot;

class Program
{
    static void Main()
    {
        // Create a new bitmap plot surface
        var plotSurface = new NPlot.Bitmap.PlotSurface2D(800, 600);

        // Create a line plot
        var linePlot = new LinePlot
        {
            AbscissaData = new double[] { 1, 2, 3, 4, 5 },
            OrdinateData = new double[] { 1, 4, 9, 16, 25 }
        };

        // Add the line plot to the plot surface
        plotSurface.Add(linePlot);

        // Customize the plot (e.g., titles, labels)
        plotSurface.Title = "Sample Plot";
        plotSurface.XAxis1.Label = "X-Axis";
        plotSurface.YAxis1.Label = "Y-Axis";

        // Refresh the plot to render it
        plotSurface.Refresh();

        // Save the plot as a PNG image
        plotSurface.Bitmap.Save("c://plot.png", System.Drawing.Imaging.ImageFormat.Png);

        Console.WriteLine("Plot saved as plot.png");
    }
}
using System;
using NPlot;

class Program
{
    static void Main()
    {
        // Create a new bitmap plot surface
        var plotSurface = new NPlot.Bitmap.PlotSurface2D(800, 600);

        // Create a line plot
        var linePlot = new LinePlot
        {
            AbscissaData = new double[] { 1, 2, 3, 4, 5 },
            OrdinateData = new double[] { 1, 4, 9, 16, 25 }
        };

        // Add the line plot to the plot surface
        plotSurface.Add(linePlot);

        // Customize the plot (e.g., titles, labels)
        plotSurface.Title = "Sample Plot";
        plotSurface.XAxis1.Label = "X-Axis";
        plotSurface.YAxis1.Label = "Y-Axis";

        // Refresh the plot to render it
        plotSurface.Refresh();

        // Save the plot as a PNG image
        plotSurface.Bitmap.Save("c://plot.png", System.Drawing.Imaging.ImageFormat.Png);

        Console.WriteLine("Plot saved as plot.png");
    }
}
$vbLabelText   $csharpLabel

Here is the output plot image:

NPlot C# (How It Works For Developers): Figure 2

Advanced Charting Techniques with NPlot

After mastering basic plots, NPlot offers a range of more complex chart types to enhance your data visualization capabilities. These include bar plots, scatter charts, and step plots, each suited for different kinds of data representation.

Utilizing Bar and Scatter Plots

Bar Plot: Ideal for displaying data values in one or more categories. Each bar represents a data value, with its height indicating the value's magnitude.

Scatter Plot: Perfect for visualizing data sets where each data point is independent. It plots data points on a two-dimensional graph, allowing for the analysis of patterns or trends.

Implementing a Step Plot

Step Plot: Used for data that involves successive abscissa values, such as time-series data. It creates a staircase-like representation, clearly showing changes between successive data points.

Integrating NPlot with IronPDF

The integration of NPlot with IronPDF allows for the seamless conversion of charts into PDF documents. IronPDF is a powerful library that enables the rendering of HTML content and plot classes into high-quality PDF files. This integration is particularly useful for applications that require generating reports or documenting analyzed data.

Get Started with IronPDF


Install IronPDF Library

Install Using NuGet Package Manager

To integrate IronPDF into your NPlot C# project using the NuGet Package manager, follow these steps:

  1. Open Visual Studio and in the solution explorer, right-click on your project.
  2. Choose “Manage NuGet packages…” from the context menu.
  3. Go to the browse tab and search IronPDF.
  4. Select the IronPDF library from the search results and click install button.
  5. Accept any license agreement prompt.

If you want to include IronPDF in your project via Package manager console, then execute the following command in Package Manager Console:

Install-Package IronPdf

It’ll fetch and install IronPDF into your project.

Install Using NuGet Website

For a detailed overview of IronPDF, including its features, compatibility, and additional download options, visit the IronPDF page on the NuGet website at https://www.nuget.org/packages/IronPdf.

Install Via DLL

Alternatively, you can incorporate IronPDF directly into your project using its dll file. Download the ZIP file containing the DLL from the IronPDF Download Page. Unzip it, and include the DLL in your project.

Generating Dynamic Charts with NPlot

NPlot excels in creating dynamic and visually appealing charts within C# applications. This section will guide you through generating a scatter chart, a typical use case for displaying data with two variables.

Scatter charts are particularly effective in visualizing the relationship between the variables. Follow these steps to create a scatter plot:

  1. Initiate Plot Surface: Start by creating a PlotSurface2D instance.
  2. Prepare Data: Gather the data values you wish to plot. Scatter charts plot individual points, so you'll need two arrays of values: one for the x-coordinates and another for the y-coordinates. You can add as many plots as you want to the PlotSurface2D.
  3. Instantiate a Scatter Plot: Use NPlot's PointPlot or ScatterPlot class to create your chart with your plot objects.
  4. Customize the Chart: Apply various customizations like setting the point styles, colors, and axes properties to make the chart informative and appealing.
using NPlot;

class Program
{
    static void Main()
    {
        var plotSurface = new NPlot.Windows.PlotSurface2D();

        // Prepare data for the scatter plot
        var scatterPlot = new PointPlot
        {
            AbscissaData = new double[] { /* x-coordinates */ },
            OrdinateData = new double[] { /* y-coordinates */ }
        };

        // Add the scatter plot to the plot surface
        plotSurface.Add(scatterPlot);

        // Customize the chart and render the plotSurface
        plotSurface.Refresh();
    }
}
using NPlot;

class Program
{
    static void Main()
    {
        var plotSurface = new NPlot.Windows.PlotSurface2D();

        // Prepare data for the scatter plot
        var scatterPlot = new PointPlot
        {
            AbscissaData = new double[] { /* x-coordinates */ },
            OrdinateData = new double[] { /* y-coordinates */ }
        };

        // Add the scatter plot to the plot surface
        plotSurface.Add(scatterPlot);

        // Customize the chart and render the plotSurface
        plotSurface.Refresh();
    }
}
$vbLabelText   $csharpLabel

Converting Charts to PDF with IronPDF

Once you have created a chart with NPlot, you can use IronPDF to convert this chart into a PDF document. This process involves rendering the chart as an image and then using IronPDF to embed this image in a PDF. You can follow these steps to convert charts to PDF:

  1. Render Chart as Image: First, convert your NPlot chart into an image format. This can be done by drawing the PlotSurface2D onto a bitmap.
  2. Create PDF with IronPDF: Use IronPDF's API to create a new PDF document and insert the chart image.
using IronPdf;

class Program
{
    static void Main()
    {
        // Assuming 'chartImagePath' is the path to the Bitmap image of your NPlot chart
        var imageFiles = new string[] { "chartImagePath" };

        // Convert image files to PDF and save the output
        ImageToPdfConverter.ImageToPdf(imageFiles).SaveAs("Chart.pdf");
    }
}
using IronPdf;

class Program
{
    static void Main()
    {
        // Assuming 'chartImagePath' is the path to the Bitmap image of your NPlot chart
        var imageFiles = new string[] { "chartImagePath" };

        // Convert image files to PDF and save the output
        ImageToPdfConverter.ImageToPdf(imageFiles).SaveAs("Chart.pdf");
    }
}
$vbLabelText   $csharpLabel

Conclusion

NPlot C# (How It Works For Developers): Figure 3

Throughout this tutorial, we've explored the integration of two powerful libraries in C#: NPlot for creating dynamic, data-driven charts from data-dependent elements, and IronPDF for converting these charts into PDF documents.

This combination provides a comprehensive toolkit for C# developers, allowing them to visualize data effectively and then seamlessly transition that data into a shareable, archival format.

Start with IronPDF's Free Trial License, available from $799.

자주 묻는 질문

NPlot이란 무엇이며 C#에서 어떻게 사용되나요?

NPlot은 C#에서 다양한 그래프와 플롯을 생성하는 데 사용되는 .NET 프레임워크의 다용도 차트 라이브러리입니다. 간단한 라인 플롯부터 복잡한 분산형 차트까지 크고 작은 데이터 집합을 시각화하는 데 이상적입니다.

C# 프로젝트에 NPlot을 설치하려면 어떻게 해야 하나요?

Visual Studio의 NuGet 패키지 관리자를 사용하여 C# 프로젝트에 NPlot을 설치할 수 있습니다. '도구' > 'NuGet 패키지 관리자' > '솔루션용 NuGet 패키지 관리...'로 이동하여 'NPlot'을 검색한 후 설치를 진행하세요.

C#에서 NPlot을 사용하여 차트를 만들려면 어떻게 해야 하나요?

NPlot으로 차트를 만들려면 PlotSurface2D 개체를 초기화하고, 데이터로 LinePlot을 만든 다음, 이를 플롯 서페이스에 추가합니다. 제목, 레이블로 사용자 지정한 다음 차트를 렌더링합니다.

NPlot에서 사용할 수 있는 고급 차트 기법에는 어떤 것이 있나요?

NPlot은 막대형 차트, 분산형 차트, 단계형 차트와 같은 고급 차트 기법을 제공하여 다양한 시각화 형식으로 데이터를 효과적으로 표현할 수 있습니다.

IronPDF는 NPlot 차트와 함께 어떻게 사용할 수 있나요?

IronPDF는 NPlot으로 만든 차트를 고품질 PDF 문서로 변환할 수 있어 보고서를 생성하거나 공유 가능한 형식으로 데이터 분석을 문서화할 때 유용합니다.

내 C# 프로젝트에 IronPDF를 추가하려면 어떻게 하나요?

프로젝트에 IronPDF를 추가하려면 Visual Studio의 NuGet 패키지 관리자를 사용하여 IronPDF를 설치하거나 IronPDF 웹사이트에서 DLL을 다운로드하여 프로젝트에 수동으로 포함하세요.

IronPDF를 사용하여 NPlot 차트를 PDF로 변환하려면 어떻게 해야 하나요?

먼저 NPlot 차트를 이미지로 렌더링합니다. 그런 다음 IronPDF의 API를 사용하여 PDF 문서를 만들고 차트 이미지를 삽입합니다. 이 과정을 통해 이미지 파일을 PDF 형식으로 쉽게 변환할 수 있습니다.

NPlot과 IronPDF를 함께 사용하면 어떤 이점이 있나요?

개발자는 IronPDF와 함께 NPlot을 사용하면 상세하고 동적인 차트를 만든 다음 보고 및 문서화를 위해 PDF로 변환하여 데이터 시각화와 아카이브 기능을 효과적으로 결합할 수 있습니다.

개발자를 위한 IronPDF 평가판이 있나요?

예, IronPDF의 무료 평가판 라이선스를 사용할 수 있으므로 개발자는 정식 라이선스를 구매하기 전에 기능을 살펴볼 수 있습니다.

커티스 차우
기술 문서 작성자

커티스 차우는 칼턴 대학교에서 컴퓨터 과학 학사 학위를 취득했으며, Node.js, TypeScript, JavaScript, React를 전문으로 하는 프론트엔드 개발자입니다. 직관적이고 미적으로 뛰어난 사용자 인터페이스를 만드는 데 열정을 가진 그는 최신 프레임워크를 활용하고, 잘 구성되고 시각적으로 매력적인 매뉴얼을 제작하는 것을 즐깁니다.

커티스는 개발 분야 외에도 사물 인터넷(IoT)에 깊은 관심을 가지고 있으며, 하드웨어와 소프트웨어를 통합하는 혁신적인 방법을 연구합니다. 여가 시간에는 게임을 즐기거나 디스코드 봇을 만들면서 기술에 대한 애정과 창의성을 결합합니다.