본문 바로가기
📁 [4] 개발자 정보 & 코드 노트/C#

C# Windows Forms 강의 13편: Chart 컨트롤로 데이터 시각화

by wawManager 2025. 2. 16.

반응형

1. 강의 개요

이번 강의에서는 Windows Forms의 Chart 컨트롤을 사용해 데이터를 시각적으로 표현하는 방법을 배웁니다.
Chart 컨트롤은 다양한 데이터 시각화 옵션(꺾은선형, 막대형, 원형 등)을 제공하여 데이터 분석 및 보고서에 활용됩니다.


2. 학습 목표

  1. Chart 컨트롤을 사용해 데이터를 시각적으로 표시.
  2. Chart의 데이터 시리즈 및 차트 종류 변경 방법 학습.
  3. Chart와 동적 데이터를 결합하여 실시간으로 업데이트되는 그래프 생성.

3. Chart (차트 컨트롤)

Chart란?

Chart 컨트롤은 데이터를 그래프로 시각화하는 데 사용됩니다.

  • 꺾은선형(Line), 막대형(Bar), 원형(Pie) 등 다양한 그래프를 지원.
  • 데이터를 Series 객체를 통해 추가하고, ChartArea로 차트 영역을 설정.

Chart 주요 구성 요소

구성 요소 설명 예제

ChartArea 차트가 표시될 영역 설정 chart1.ChartAreas.Add(new ChartArea("MainArea"));
Series 차트 데이터 시리즈를 정의 chart1.Series.Add(new Series("Data1"));
Legend 차트 범례 표시 chart1.Legends.Add(new Legend("Legend1"));

Series 주요 속성

속성 설명 예제

ChartType 차트 유형 설정 (Line, Bar 등) series1.ChartType = SeriesChartType.Line;
Points 데이터 점 추가 series1.Points.AddXY(1, 100);

4. 실습: Chart로 데이터 시각화하기

요구사항

  1. Chart 컨트롤을 사용해 꺾은선형(Line) 그래프를 생성.
  2. 버튼 클릭 시 차트 데이터를 동적으로 업데이트.
  3. 차트 범례를 사용해 데이터 항목을 구분.

폼 구성

컨트롤 타입 이름 텍스트 위치 크기

Chart chart1 (없음) 폼 상단 (400 x 300)
Button btnUpdate "데이터 추가" 폼 하단 (150 x 30)

코드 작성

Form1.cs

using System;
using System.Windows.Forms;
using System.Windows.Forms.DataVisualization.Charting;

namespace WindowsFormsApp1
{
    public partial class Form1 : Form
    {
        private int currentX = 1; // X축 초기 값

        public Form1()
        {
            InitializeComponent();
            InitializeChart();
        }

        private void InitializeChart()
        {
            // ChartArea 추가
            ChartArea chartArea = new ChartArea("MainArea");
            chart1.ChartAreas.Add(chartArea);

            // Series 추가
            Series series = new Series("Sales Data");
            series.ChartType = SeriesChartType.Line; // 꺾은선형 그래프
            series.Points.AddXY(0, 0); // 초기 데이터 추가
            chart1.Series.Add(series);

            // Legend 추가
            Legend legend = new Legend("MainLegend");
            chart1.Legends.Add(legend);

            // Chart 초기 설정
            chart1.Dock = DockStyle.Top;
            chart1.Height = 300;
        }

        private void BtnUpdate_Click(object sender, EventArgs e)
        {
            // 데이터 추가
            Random random = new Random();
            int newY = random.Next(10, 100); // 10 ~ 100 사이의 랜덤 값 생성
            chart1.Series["Sales Data"].Points.AddXY(currentX, newY);
            currentX++;

            MessageBox.Show($"X={currentX - 1}, Y={newY} 데이터가 추가되었습니다.", "데이터 추가");
        }
    }
}

디자이너 코드: Form1.Designer.cs

namespace WindowsFormsApp1
{
    partial class Form1
    {
        private System.ComponentModel.IContainer components = null;
        private System.Windows.Forms.DataVisualization.Charting.Chart chart1;
        private System.Windows.Forms.Button btnUpdate;

        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }

        private void InitializeComponent()
        {
            this.chart1 = new System.Windows.Forms.DataVisualization.Charting.Chart();
            this.btnUpdate = new System.Windows.Forms.Button();
            ((System.ComponentModel.ISupportInitialize)(this.chart1)).BeginInit();
            this.SuspendLayout();
            // 
            // chart1
            // 
            this.chart1.Location = new System.Drawing.Point(10, 10);
            this.chart1.Name = "chart1";
            this.chart1.Size = new System.Drawing.Size(500, 300);
            this.chart1.TabIndex = 0;
            this.chart1.Text = "chart1";
            // 
            // btnUpdate
            // 
            this.btnUpdate.Location = new System.Drawing.Point(10, 320);
            this.btnUpdate.Name = "btnUpdate";
            this.btnUpdate.Size = new System.Drawing.Size(150, 30);
            this.btnUpdate.TabIndex = 1;
            this.btnUpdate.Text = "데이터 추가";
            this.btnUpdate.UseVisualStyleBackColor = true;
            this.btnUpdate.Click += new System.EventHandler(this.BtnUpdate_Click);
            // 
            // Form1
            // 
            this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 20F);
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            this.ClientSize = new System.Drawing.Size(520, 370);
            this.Controls.Add(this.btnUpdate);
            this.Controls.Add(this.chart1);
            this.Name = "Form1";
            this.Text = "Chart 컨트롤 예제";
            ((System.ComponentModel.ISupportInitialize)(this.chart1)).EndInit();
            this.ResumeLayout(false);
        }
    }
}

6. 실행 결과

  1. Chart
    • 꺾은선형 그래프가 표시됩니다.
    • 기본 데이터 (0, 0)으로 시작.
  2. 데이터 추가 버튼
    • "데이터 추가" 버튼 클릭 시 새로운 X, Y 데이터가 그래프에 추가됩니다.
    • 예:
      X=1, Y=45 데이터가 추가되었습니다.
      X=2, Y=78 데이터가 추가되었습니다.
      

7. 주요 개념 요약

  1. Chart 컨트롤은 데이터를 시각적으로 표현하는 강력한 도구입니다.
  2. Series는 차트의 데이터를 나타내며, ChartType을 사용해 그래프 유형을 지정합니다.
  3. Chart와 동적 데이터를 결합하면 실시간으로 업데이트되는 그래프를 구현할 수 있습니다.

 

반응형