본문 바로가기

Android/UI

[안드로이드] 실시간 차트(그래프), Real-time Chart 그리기

728x90
반응형

 

 

유명한 라이브러리 MPAndroid Chart를 이용하여 Real-time chart를 그려보았습니다.

밑의 코드는 위의 영상의 코드와 정확히 같지는 않지만(색상, description등) 실시간 차트를 그리기 위한 예시입니다.

위의 영상은 TCP/IP로 데이터를 받아 실시간 차트를 그렸습니다.

 

 

 

Gradle 추가


repositories {
    maven { url 'https://jitpack.io' }
}
dependencies {
    ...
    implementation 'com.github.PhilJay:MPAndroidChart:v3.1.0'
    ...
}

build.gradle(Moudle:app) 에 위처럼 추가해 줍니다.

repositories는 dependencies위에 추가하여 써주면 됩니다.


 

Layout


<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="380dp">

    <com.github.mikephil.charting.charts.LineChart
        android:id="@+id/LineChart"
        android:layout_width="match_parent"
        android:layout_height="match_parent"/>

</FrameLayout>

Line Chart layout을 추가하였습니다.

 


 

Chart Code


차트 생성하기 위해 onCreate와 같은 곳에 코드를 입력해줍니다.

차트의 색상이나, X축, Y축의 기본 설정을 할 수 있습니다.

private LineChart chart;
...

chart = (LineChart) view.findViewById(R.id.LineChart);

chart.setDrawGridBackground(true);
chart.setBackgroundColor(Color.BLACK);
chart.setGridBackgroundColor(Color.BLACK);

// description text
chart.getDescription().setEnabled(true);
Description des = chart.getDescription();
des.setEnabled(true);
des.setText("Real-Time DATA");
des.setTextSize(15f);
des.setTextColor(Color.WHITE);

// touch gestures (false-비활성화)
chart.setTouchEnabled(false);

// scaling and dragging (false-비활성화)
chart.setDragEnabled(false);
chart.setScaleEnabled(false);

//auto scale
chart.setAutoScaleMinMaxEnabled(true);

// if disabled, scaling can be done on x- and y-axis separately
chart.setPinchZoom(false);

//X축
chart.getXAxis().setDrawGridLines(true);
chart.getXAxis().setDrawAxisLine(false);

chart.getXAxis().setEnabled(true);
chart.getXAxis().setDrawGridLines(false);

//Legend
Legend l = chart.getLegend();
l.setEnabled(true);
l.setFormSize(10f); // set the size of the legend forms/shapes
l.setTextSize(12f);
l.setTextColor(Color.WHITE);

//Y축
YAxis leftAxis = chart.getAxisLeft();
leftAxis.setEnabled(true);
leftAxis.setTextColor(getResources().getColor(R.color.colorGrid));
leftAxis.setDrawGridLines(true);
leftAxis.setGridColor(getResources().getColor(R.color.colorGrid));

YAxis rightAxis = chart.getAxisRight();
rightAxis.setEnabled(false);


// don't forget to refresh the drawing
chart.invalidate();

초기 설정은 autoScale로 한것을 볼 수 있지만, setAxisMaximum(), setAxisMinimum()을 이용하여 X축과 Y축의 min과 max값을 따로 설정해줄 수 있습니다.

라인 데이터 생성에 필요한 함수들을 만들어줍니다.

 private void addEntry(double num) {

        LineData data = chart.getData();

        if (data == null) {
            data = new LineData();
            chart.setData(data);
        }

        ILineDataSet set = data.getDataSetByIndex(0);
        // set.addEntry(...); // can be called as well

        if (set == null) {
            set = createSet();
            data.addDataSet(set);
        }



        data.addEntry(new Entry((float)set.getEntryCount(), (float)num), 0);
        data.notifyDataChanged();

        // let the chart know it's data has changed
        chart.notifyDataSetChanged();

        chart.setVisibleXRangeMaximum(150);
        // this automatically refreshes the chart (calls invalidate())
        chart.moveViewTo(data.getEntryCount(), 50f, YAxis.AxisDependency.LEFT);

    }

    private LineDataSet createSet() {



        LineDataSet set = new LineDataSet(null, "Real-time Line Data");
        set.setLineWidth(1f);
        set.setDrawValues(false);
        set.setValueTextColor(getResources().getColor(Color.WHITE));
        set.setColor(getResources().getColor(Color.WHITE));
        set.setMode(LineDataSet.Mode.LINEAR);
        set.setDrawCircles(false);
        set.setHighLightColor(Color.rgb(190, 190, 190));

        return set;
    }

 

 

setVisibleXRangeMaximum(150);  함수를 이용하여 X축 표시 범위를 조절합니다. 한번에 150개를 그려줍니다.

 

이제, 실시간으로 데이터를 추가하며 차트를 그릴 수 있습니다. 

addEntry(datanum);

 

 실시간으로 데이터를 받아와 위 코드만 입력해주면 실시간 차트를 만들 수 있습니다.

저는 addEntry 함수 데이터를 double형으로 받게 하였지만 차트를 그리기 위해서는 float형으로 변형해 주어야 합니다.

addEntry함수를 필요에 맞게 변형하여 사용해보세요.

또한 주의할 점을 데이터를 받고 그리기 위해 thread(스레드) 안에서 사용하였다면 차트 그리는 것도 UI변경이므로 runOnUIThread를 사용하여야 합니다.

runOnUiThread(new Runnable() {
    public void run() {
        addEntry(datanum);
    }
});

필요한 메서드 들과 예제 소스들은 아래 MPAndroidChart github 링크를 참조하세요.

 


 

 

참고 문서

 

 

 

728x90
반응형