zoukankan      html  css  js  c++  java
  • 最牛逼android上的图表库MpChart(三) 条形图

     

    最牛逼android上的图表库MpChart(三) 条形图

    最近工作中,用到了mpchart图表库,现在分享受下mpchart图表库的各个图表在实际工作应用场景:

    附上mpandroidchartlibrary-2-1-6.jar的下载链接http://download.csdn.net/detail/hejjunlin/9561829

    使用mpchart jar包:mpandroidchartlibrary-2-1-6.jar 
    如果是在studio下,进行如下引用: 
    repositories { 
    maven { url “https://jitpack.io” } 
    }

    dependencies { 
    compile ‘com.github.PhilJay:MPAndroidChart:v2.1.6’ 
    }

    BarChart条形图介绍

    • BarChart类
    • 使用哪些API

    BarChart条形图实例

      • 布局文件
      • Java代码
     1 <?xml version="1.0" encoding="utf-8"?>
     2 <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
     3     android:layout_width="match_parent"
     4     android:layout_height="match_parent" >
     5 
     6     <com.github.mikephil.charting.charts.BarChart
     7         android:id="@+id/chart1"
     8         android:layout_width="match_parent"
     9         android:layout_height="match_parent" />
    10 
    11 </RelativeLayout>
      1 package com.example.mpchart;
      2 
      3 import java.util.ArrayList;
      4 import java.util.List;
      5 
      6 import android.annotation.SuppressLint;
      7 import android.app.Activity;
      8 import android.graphics.Color;
      9 import android.graphics.PointF;
     10 import android.graphics.RectF;
     11 import android.graphics.Typeface;
     12 import android.os.Bundle;
     13 import android.os.Handler;
     14 import android.os.Looper;
     15 import android.os.Message;
     16 import android.util.Log;
     17 import android.view.WindowManager;
     18 
     19 import com.example.mpchart.data.ErrorCodePercentDataSource;
     20 import com.example.mpchart.data.IDataSource;
     21 import com.example.mpchart.data.IDataSource.onDataChangedListener;
     22 import com.example.mpchart.utils.DBHelper;
     23 import com.example.mpchart.utils.DateUtils;
     24 import com.example.mpchart.utils.LogUtils;
     25 import com.github.mikephil.charting.charts.BarChart;
     26 import com.github.mikephil.charting.components.Legend;
     27 import com.github.mikephil.charting.components.Legend.LegendDirection;
     28 import com.github.mikephil.charting.components.Legend.LegendForm;
     29 import com.github.mikephil.charting.components.Legend.LegendPosition;
     30 import com.github.mikephil.charting.components.XAxis;
     31 import com.github.mikephil.charting.components.XAxis.XAxisPosition;
     32 import com.github.mikephil.charting.components.YAxis;
     33 import com.github.mikephil.charting.components.YAxis.AxisDependency;
     34 import com.github.mikephil.charting.components.YAxis.YAxisLabelPosition;
     35 import com.github.mikephil.charting.data.BarData;
     36 import com.github.mikephil.charting.data.BarDataSet;
     37 import com.github.mikephil.charting.data.BarEntry;
     38 import com.github.mikephil.charting.data.Entry;
     39 import com.github.mikephil.charting.formatter.YAxisValueFormatter;
     40 import com.github.mikephil.charting.highlight.Highlight;
     41 import com.github.mikephil.charting.listener.OnChartValueSelectedListener;
     42 import com.github.mikephil.charting.utils.ColorTemplate;
     43 
     44 public class BarChartActivity extends Activity implements OnChartValueSelectedListener {
     45 
     46     private static final String TAG = "BarChartActivity";
     47     protected BarChart mChart;
     48     private IDataSource mDataSource = new ErrorCodePercentDataSource();
     49     private String mDateTime;
     50 
     51     private Typeface mTf;
     52 
     53     private Handler mHandler = new Handler(Looper.getMainLooper()) {
     54         @Override
     55         public void handleMessage(Message msg) {
     56             super.handleMessage(msg);
     57             getData();
     58         }
     59     };
     60 
     61     @Override
     62     protected void onCreate(Bundle savedInstanceState) {
     63         super.onCreate(savedInstanceState);
     64         getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
     65         setContentView(R.layout.activity_barchart);
     66 
     67         mChart = (BarChart) findViewById(R.id.chart1);
     68         mChart.setOnChartValueSelectedListener(this);
     69         mChart.setDescription(""/*mDataSource.getDescription()*/);
     70         mChart.setDescriptionTextSize(30);
     71 //        mChart.setDescriptionPosition(960, 550);
     72 
     73         mChart.setDrawBarShadow(false);
     74         mChart.setDrawValueAboveBar(true);
     75 
     76         // if more than 60 entries are displayed in the chart, no values will be
     77         // drawn
     78         mChart.setMaxVisibleValueCount(60);
     79 
     80         // scaling can now only be done on x- and y-axis separately
     81         mChart.setPinchZoom(false);
     82 
     83         mChart.setDrawGridBackground(false);
     84         // mChart.setDrawYLabels(false);
     85 
     86         mTf = Typeface.createFromAsset(getAssets(), "OpenSans-Regular.ttf");
     87 
     88         XAxis xAxis = mChart.getXAxis();
     89         xAxis.setPosition(XAxisPosition.BOTTOM);
     90         xAxis.setTypeface(mTf);
     91         xAxis.setDrawGridLines(false);
     92         xAxis.setSpaceBetweenLabels(2);
     93 
     94         YAxisValueFormatter custom = new MyYAxisValueFormatter();//设置Y轴上的显示单位
     95 
     96         YAxis leftAxis = mChart.getAxisLeft();
     97         leftAxis.setTypeface(mTf);
     98         leftAxis.setLabelCount(8, false);
     99         leftAxis.setValueFormatter(custom);
    100         leftAxis.setPosition(YAxisLabelPosition.OUTSIDE_CHART);
    101         leftAxis.setSpaceTop(15f);
    102         leftAxis.setAxisMinValue(0f); // this replaces setStartAtZero(true)
    103 
    104         YAxis rightAxis = mChart.getAxisRight();
    105         rightAxis.setDrawGridLines(false);
    106         rightAxis.setTypeface(mTf);
    107         rightAxis.setLabelCount(8, false);
    108         rightAxis.setValueFormatter(custom);
    109         rightAxis.setSpaceTop(15f);
    110         rightAxis.setAxisMinValue(0f); // this replaces setStartAtZero(true)
    111 
    112         Legend l = mChart.getLegend();
    113         l.setPosition(LegendPosition.BELOW_CHART_LEFT);
    114         l.setForm(LegendForm.SQUARE);
    115         l.setFormSize(9f);
    116         l.setTextSize(11f);
    117         l.setXEntrySpace(4f);
    118 
    119         getData();
    120         new Thread(mRunnable).start();
    121         // mChart.setDrawLegend(false);
    122     }
    123 
    124     private Runnable mRunnable = new Runnable() {
    125         @Override
    126         public void run() {
    127             while(true) {
    128                   try {
    129                        Thread.sleep(15*1000);//15s刷新下数据
    130                        mHandler.sendMessage(mHandler.obtainMessage());
    131                    } catch (InterruptedException e) {
    132                        e.printStackTrace();
    133                   }
    134                   }
    135         }
    136     };
    137 
    138     private onDataChangedListener listener = new onDataChangedListener() {
    139 
    140         @Override
    141         public void onChanged(String[] xx, String[] yy) {
    142             notifyDataChanged(xx, yy);
    143         }
    144     };
    145 
    146     private void getData() {
    147         LogUtils.d(TAG, "getData() " + DateUtils.getCurrentDate()); 
    148         new Thread(new Runnable() {
    149             @Override
    150             public void run() {
    151                 DBHelper.getInstance().init();
    152                 String table = "error_info_" + DateUtils.get2HoursDate();
    153                 String sql = "select *from " + table + " limit 20"/* + DateUtils.get2HoursDate()*/;
    154                 boolean isexist = DBHelper.getInstance().isTableExist(table);
    155                 if (isexist) {
    156                     mDateTime = DateUtils.get2HoursDate();
    157                     final String[] xx = DBHelper.getInstance().query(sql,3); 
    158                     final String[] yy = DBHelper.getInstance().query(sql,5);
    159                     mHandler.post(new Runnable() {
    160                         @Override
    161                         public void run() {
    162                             listener.onChanged(xx, yy);
    163                         }
    164                     });
    165                 } else {
    166                     String table2 = "error_info_" + DateUtils.getOneHoursAgoTime();
    167                     mDateTime = DateUtils.getOneHoursAgoTime();
    168                     String sql2 = "select *from " + table2 + " limit 20";
    169                     LogUtils.d(TAG, "getData() sql2 " + sql2); 
    170                     final String[] xx = DBHelper.getInstance().query(sql2,3); 
    171                     final String[] yy = DBHelper.getInstance().query(sql2,5);
    172                     mHandler.post(new Runnable() {
    173                         @Override
    174                         public void run() {
    175                             listener.onChanged(xx, yy);
    176                         }
    177                     });
    178                 }
    179             }
    180         }).start();
    181     }
    182 
    183     private void notifyDataChanged(String[] xx, String[] yy) {
    184         Typeface tf = Typeface.createFromAsset(getAssets(),"OpenSans-Regular.ttf");
    185        // 加载数据
    186         setData(xx,yy );
    187         //从X轴进入的动画
    188         mChart.animateX(2000);
    189 //        mChart.animateY(2000);   //从Y轴进入的动画
    190 //        mChart.animateXY(2000, 2000);    //从XY轴一起进入的动画
    191 
    192         //设置最小的缩放
    193          mChart.setScaleMinima(0.5f, 1f);
    194         //设置视口
    195         // mChart.centerViewPort(10, 50);
    196 
    197         // get the legend (only possible after setting data)
    198         Legend l = mChart.getLegend();
    199         l.setForm(LegendForm.LINE);  //设置图最下面显示的类型
    200         l.setTypeface(tf);  
    201         l.setTextSize(30);
    202         l.setTextColor(Color.rgb(244, 117, 117));
    203         l.setDirection(LegendDirection.LEFT_TO_RIGHT);
    204         l.setYOffset(660);
    205         l.setFormSize(20f); // set the size of the legend forms/shapes
    206 
    207         // 刷新图表
    208         mChart.invalidate();
    209     }
    210 
    211     private void setData(String[] xx, String[] yy) {
    212 
    213         ArrayList<String> xVals = new ArrayList<String>();
    214         for (int i = 0; i < xx.length; i++) {
    215             xVals.add(xx[i]);
    216         }
    217 
    218         ArrayList<BarEntry> yVals1 = new ArrayList<BarEntry>();
    219 
    220         for (int i = 0; i < yy.length; i++) {
    221             float y = Float.parseFloat(yy[i]);
    222             yVals1.add(new BarEntry(y, i));//填充数据
    223         }
    224 
    225         BarDataSet set1;
    226         mChart.animateY(2000);//设置动画
    227         set1 = new BarDataSet(yVals1, "DataSet");
    228         set1.setBarSpacePercent(35f);
    229         set1.setColors(ColorTemplate.LIBERTY_COLORS);
    230 
    231 
    232         BarDataSet dataSets = new BarDataSet(yVals1, "错误码占比监控,数据来源: + mDateTime);
    233         List<Integer> list = new ArrayList<Integer>();
    234         list.add(Color.rgb(179, 48, 80));//设置颜色
    235         list.add(Color.rgb(106, 167, 134));
    236         list.add(Color.rgb(53, 194, 209));
    237         list.add(Color.rgb(118, 174, 175));
    238         list.add(Color.rgb(42, 109, 130));
    239         list.add(Color.rgb(106, 150, 31));
    240         list.add(Color.rgb(179, 100, 53));
    241         list.add(Color.rgb(193, 37, 82));
    242         list.add(Color.rgb(255, 102, 0));
    243         list.add(Color.rgb(217, 80, 138));
    244         list.add(Color.rgb(254, 149, 7));
    245         list.add(Color.rgb(254, 247, 120));
    246         dataSets.setColors(list);
    247 
    248         BarData data = new BarData(xVals, dataSets);
    249         data.setValueTextSize(10f);
    250         data.setValueTypeface(mTf);
    251 
    252         mChart.setData(data);
    253     }
    254 
    255     @SuppressLint("NewApi")
    256     @Override
    257     public void onValueSelected(Entry e, int dataSetIndex, Highlight h) {
    258 
    259         if (e == null)
    260             return;
    261 
    262         RectF bounds = mChart.getBarBounds((BarEntry) e);
    263         PointF position = mChart.getPosition(e, AxisDependency.LEFT);
    264 
    265         Log.i("bounds", bounds.toString());
    266         Log.i("position", position.toString());
    267 
    268         Log.i("x-index",
    269                 "low: " + mChart.getLowestVisibleXIndex() + ", high: "
    270                         + mChart.getHighestVisibleXIndex());
    271     }
    272 
    273     public void onNothingSelected() {
    274     };
    275 }

    BarChart效果

    这里写图片描述

     
     
  • 相关阅读:
    Sum Root to Leaf Numbers
    Sum Root to Leaf Numbers
    Sort Colors
    Partition List
    Binary Tree Inorder Traversal
    Binary Tree Postorder Traversal
    Remove Duplicates from Sorted List II
    Remove Duplicates from Sorted List
    Search a 2D Matrix
    leetcode221
  • 原文地址:https://www.cnblogs.com/huolongluo/p/6094833.html
Copyright © 2011-2022 走看看