2018-03-08

圖表控件庫 MPAndroidChart 的使用

使用方法

  • 在build.gradle的dependencies節(jié)點中加入如下代碼

      dependencies {
          compile fileTree(include: ['*.jar'], dir: 'libs')
          compile 'com.github.PhilJay:MPAndroidChart:v3.0.2'
      }
    
  • 跟目錄的build.gradle的repositories節(jié)點中加入如下代碼

     maven { url 'https://maven.google.com' }
    

示例

柱狀圖

效果圖
xgz.png
  • 在XML中加入如下代碼

      <com.github.mikephil.charting.charts.BarChart
                  android:id="@+id/chart_there"
                  android:layout_width="match_parent"
                  android:layout_height="200dp"
                  android:layout_marginTop="20dp"
                  android:layout_marginRight="20dp"
                  android:layout_marginLeft="20dp"
                  android:background="@color/white"
                  />
    
  • 柱狀圖自定義顏色的替換

       /**
        * @param mBarChart 柱狀圖顏色的替換
        */
          public void afa(BarChart mBarChart){
              BarChartShapeRender renderer = new BarChartShapeRender(mBarChart, mBarChart.getAnimator(), mBarChart.getViewPortHandler());
              //柱狀圖顏色
              renderer.setBarDrawable(getResources().getDrawable(R.drawable.shape_bar_chart));
              //點擊后的顏色腊尚,Y超過20000的顏色
              renderer.setWarnBarDrawable(20000,getResources().getDrawable(R.drawable.shape_bar_common));
      mBarChart.setRenderer(renderer);
           }
    
  • 主要代碼以及數(shù)據(jù)的設(shè)置

      public static void drawOne(BarChart mBarChart_One){
              ArrayList<String> mlist=new ArrayList<String>();
              Random random = new Random();
              //模擬數(shù)據(jù),X數(shù)據(jù)
              ArrayList<BarEntry> yVals1 = new ArrayList<BarEntry>();
              for (int i = 0; i < 7; i++) {//添加數(shù)據(jù)源
                  yVals1.add(new BarEntry( i+1,random.nextInt(25000)));
              }
              mBarChart_One.setTouchEnabled(true);//是否可點擊
              mBarChart_One.setDrawBarShadow(false);//表不要陰影
              mBarChart_One.setOnChartValueSelectedListener(new OnChartValueSelectedListener() {
                       @Override
                       public void onValueSelected(Entry e, Highlight h) {
                           Log.e("---->",e.getX()+"  "+e.getY());
                       }
    
                       @Override
                       public void onNothingSelected() {
               
                       }
                   });
              mBarChart_One.setDrawValueAboveBar(true);//true文字繪畫在bar上
              Description description=new Description();
              description.setText("");
              mBarChart_One.getDescription().setEnabled(false);
              mBarChart_One.setDescription(description);  //表的描述信息
    
              mBarChart_One.setPinchZoom(false);//false只能單軸縮放
              mBarChart_One.setMaxVisibleValueCount(31); //最大顯示的個數(shù)掰盘。超過60個將不再顯示
              mBarChart_One.setScaleEnabled(false);     //禁止縮放
              mBarChart_One.setDragEnabled(true);// 是否可以拖拽
              mBarChart_One.setHighlightPerDragEnabled(true);// 拖拽超過圖標繪制畫布時高亮顯示
              mBarChart_One.setDrawGridBackground(false); // 是否顯示表格顏色
              mBarChart_One.setGridBackgroundColor(Color.RED); // 表格的的顏色
              mBarChart_One.zoom(1f,1f,0,0);//設(shè)置x,y縮放比例
              //X軸 樣式
              final XAxis xAxis = mBarChart_One.getXAxis();
              xAxis.setPosition(XAxis.XAxisPosition.BOTTOM);
              xAxis.setLabelRotationAngle(60);//柱的下面描述文字  旋轉(zhuǎn)90度
              xAxis.setDrawLabels(true);
              xAxis.setDrawGridLines(false);
              xAxis.setGranularity(20f);//設(shè)置最小間隔,防止當放大時帐姻,出現(xiàn)重復(fù)標簽酒觅。
              xAxis.setCenterAxisLabels(true);//字體下面的標簽 顯示在每個直方圖的中間
              xAxis.setLabelCount(8,true);//一個界面顯示10個Lable。那么這里要設(shè)置11個
              xAxis.setTextSize(8f);
    
              mBarChart_One.getAxisRight().setEnabled(false);//右側(cè)不顯示Y軸
              mBarChart_One.getAxisLeft().setAxisMinValue(0.0f);//設(shè)置Y軸顯示最小值薄翅,不然0下面會有空隙
              mBarChart_One.getAxisLeft().setDrawGridLines(true);//不設(shè)置Y軸網(wǎng)格
              mBarChart_One.getAxisLeft().setTextSize(8f);
    
              //.設(shè)置比例圖標的顯示隱藏
              Legend l = mBarChart_One.getLegend();
              l.setVerticalAlignment(Legend.LegendVerticalAlignment.TOP);
              l.setHorizontalAlignment(Legend.LegendHorizontalAlignment.LEFT);
              l.setOrientation(Legend.LegendOrientation.HORIZONTAL);
              l.setDrawInside(false);
              //樣式
              l.setForm(Legend.LegendForm.CIRCLE);
              //字體
              l.setFormSize(10f);
              //大小
              l.setTextSize(13f);
              l.setFormToTextSpace(10f);
              l.setXEntrySpace(10f);
              //模擬數(shù)據(jù)沙兰,Y數(shù)據(jù)
              for(int i=1;i<=yVals1.size();i++) {
                  mlist.add("10/0"+i);
              }
              IAxisValueFormatter ix=new         MyXAxisValueFormatter1(mlist);
              mBarChart_One.getXAxis().setValueFormatter(ix);
              //設(shè)置左上方的色塊和文字
              BarDataSet set1;
    
              = new BarDataSet(yVals1, "未達標  已達標");
              set1.setValueTextSize(8f);
              int [] ff=new int[2];    ff[0]=App.getAppContext().getResources().getColor(R.color.blues);
              ff[1]=App.getAppContext().getResources().getColor(R.color.To_be_evaluated);
              set1.setColors(ff);
    
    
              ArrayList<IBarDataSet> dataSets = new ArrayList<>();
              dataSets.add(set1);
              BarData data = new BarData(dataSets);
              data.setValueTextSize(10f);
              data.setBarWidth(0.3f);
              mBarChart_One.setData(data);
          }
    
  • 基本屬性介紹

      //設(shè)置背景顏色
              mBarChart.setBackgroundColor(getResources().getColor(R.color.colorAccent));
              //設(shè)置數(shù)值選擇的監(jiān)聽
              mBarChart.setOnChartValueSelectedListener(new OnChartValueSelectedListener() {
                  @Override public void onValueSelected(Entry e, Highlight h) {
      
                  }
    
                  @Override public void onNothingSelected() {
    
                  }
              });
              //設(shè)置高亮顯示
              mBarChart.setHighlightFullBarEnabled(true);
              mBarChart.setDrawValueAboveBar(true);
              //設(shè)置支持觸控
              mBarChart.setTouchEnabled(true);
              //設(shè)置是否支持拖拽
              mBarChart.setDragEnabled(true);
              //設(shè)置能否縮放
              mBarChart.setScaleEnabled(true);
              //設(shè)置true支持兩個指頭向X、Y軸的縮放翘魄,如果為false鼎天,只能支持X或者Y軸的當方向縮放
              mBarChart.setPinchZoom(true);
              //獲取圖表右下角的描述性文字,setEnable()默認為true
              mBarChart.getDescription().setEnabled(true);
              Description description=new Description();
              description.setText("description");
              //設(shè)置右下角的描述文字
              mBarChart.setDescription(description);
              //設(shè)置陰影
              mBarChart.setDrawBarShadow(false);
              //設(shè)置所有的數(shù)值在圖形的上面,而不是圖形上
              mBarChart.setDrawValueAboveBar(true);
              //設(shè)置最大的能夠在圖表上顯示數(shù)字的圖數(shù)
              mBarChart.setMaxVisibleValueCount(60);
              //設(shè)置背景是否網(wǎng)格顯示
              mBarChart.setDrawGridBackground(false);
      //X軸的數(shù)據(jù)格式
              IAxisValueFormatter xAxisFormatter = new DayAxisValueFormatter(mChart);
              //得到X軸暑竟,設(shè)置X軸的樣式
              XAxis xAxis = mChart.getXAxis();
              //設(shè)置位置
              xAxis.setPosition(XAxisPosition.BOTTOM);
              //設(shè)置特定的標簽類型
              xAxis.setTypeface(mTfLight);
              //設(shè)置是否繪制網(wǎng)格線
              xAxis.setDrawGridLines(false);
              //設(shè)置最小的區(qū)間斋射,避免標簽的迅速增多
              xAxis.setGranularity(1f); // only intervals of 1 day
              //設(shè)置進入時的標簽數(shù)量
              xAxis.setLabelCount(7);
              //設(shè)置數(shù)據(jù)格式
              xAxis.setValueFormatter(xAxisFormatter);
    
              IAxisValueFormatter custom = new MyAxisValueFormatter();
    
              YAxis leftAxis = mChart.getAxisLeft();
              leftAxis.setTypeface(mTfLight);
              leftAxis.setLabelCount(8, false);
              leftAxis.setValueFormatter(custom);
              leftAxis.setPosition(YAxisLabelPosition.OUTSIDE_CHART);
              //Sets the top axis space in percent of the full range. Default 10f
              leftAxis.setSpaceTop(15f);
              //設(shè)置Y軸最小的值
              leftAxis.setAxisMinimum(0f); // this replaces setStartAtZero(true)
    
              YAxis rightAxis = mChart.getAxisRight();
              rightAxis.setDrawGridLines(false);
              rightAxis.setTypeface(mTfLight);
              rightAxis.setLabelCount(8, false);
              rightAxis.setValueFormatter(custom);
              rightAxis.setSpaceTop(15f);
              rightAxis.setAxisMinimum(0f); // this replaces setStartAtZero(true)
              //設(shè)置圖例樣式,默認可以顯示,設(shè)置setEnabled(false)罗岖;可以不繪制
              Legend l = mChart.getLegend();
              l.setVerticalAlignment(Legend.LegendVerticalAlignment.BOTTOM);
              l.setHorizontalAlignment(Legend.LegendHorizontalAlignment.LEFT);
              l.setOrientation(Legend.LegendOrientation.HORIZONTAL);
              l.setDrawInside(false);
              l.setForm(LegendForm.SQUARE);
              l.setFormSize(9f);
              l.setTextSize(11f);
              l.setXEntrySpace(4f);
               //設(shè)置X軸和Y軸顯示的刻度
              private void setData(int count, float range) {
    
                     float start = 1f;
    
                      ArrayList<BarEntry> yVals1 = new ArrayList<BarEntry>();
    
                      for (int i = (int) start; i < start + count + 1; i++) {
                          float mult = (range + 1);
                          float val = (float) (Math.random() * mult);
                          yVals1.add(new BarEntry(i, val));
                      }
      
                      BarDataSet set1;
    
              if (mChart.getData() != null &&
              mChart.getData().getDataSetCount() > 0) {
                  set1 = (BarDataSet) mChart.getData().getDataSetByIndex(0);
                  set1.setValues(yVals1);
                  mChart.getData().notifyDataChanged();
                  mChart.notifyDataSetChanged();
              } else {
                  set1 = new BarDataSet(yVals1, "The year 2017");
                  set1.setColors(ColorTemplate.MATERIAL_COLORS);
    
                  ArrayList<IBarDataSet> dataSets = new ArrayList<IBarDataSet>();
                  dataSets.add(set1);
    
                  BarData data = new BarData(dataSets);
                  data.setValueTextSize(10f);
                  data.setValueTypeface(mTfLight);
                  data.setBarWidth(0.9f);
    
                  mChart.setData(data);
              }
          }
    
  • 基本屬性

      //設(shè)置背景顏色
              mBarChart.setBackgroundColor(getResources().getColor(R.color.colorAccent));
              //BarChart的點擊事件
              mBarChart.setOnClickListener(new View.OnClickListener() {
                  @Override public void onClick(View view) {
    
                  }
              });
              //設(shè)置數(shù)值選擇的監(jiān)聽
              mBarChart.setOnChartValueSelectedListener(new OnChartValueSelectedListener() {
                  @Override public void onValueSelected(Entry e, Highlight h) {
    
                  }
      
                  @Override public void onNothingSelected() {
    
                  }
              });
              //設(shè)置高亮顯示
              mBarChart.setHighlightFullBarEnabled(true);
              mBarChart.setDrawValueAboveBar(true);
              //設(shè)置支持觸控
              mBarChart.setTouchEnabled(true);
              //設(shè)置是否支持拖拽
              mBarChart.setDragEnabled(true);
              //設(shè)置能否縮放
              mBarChart.setScaleEnabled(true);
              //設(shè)置true支持兩個指頭向X涧至、Y軸的縮放,如果為false桑包,只能支持X或者Y軸的當方向縮放
              mBarChart.setPinchZoom(true);
              //獲取圖表右下角的描述性文字南蓬,setEnable()默認為true
              mBarChart.getDescription().setEnabled(true);
              Description description=new Description();
              description.setText("description");
              //設(shè)置右下角的描述文字
              mBarChart.setDescription(description);
              //設(shè)置陰影
              mBarChart.setDrawBarShadow(false);
              //設(shè)置所有的數(shù)值在圖形的上面,而不是圖形上
              mBarChart.setDrawValueAboveBar(true);
              //設(shè)置最大的能夠在圖表上顯示數(shù)字的圖數(shù)
              mBarChart.setMaxVisibleValueCount(60);
              //設(shè)置背景是否網(wǎng)格顯示
              mBarChart.setDrawGridBackground(false);
      //X軸的數(shù)據(jù)格式
              IAxisValueFormatter xAxisFormatter = new DayAxisValueFormatter(mChart);
              //得到X軸,設(shè)置X軸的樣式
              XAxis xAxis = mChart.getXAxis();
              //設(shè)置位置
              xAxis.setPosition(XAxisPosition.BOTTOM);
              //設(shè)置特定的標簽類型
              xAxis.setTypeface(mTfLight);
              //設(shè)置是否繪制網(wǎng)格線
              xAxis.setDrawGridLines(false);
              //設(shè)置最小的區(qū)間捡多,避免標簽的迅速增多
              xAxis.setGranularity(1f); // only intervals of 1 day
              //設(shè)置進入時的標簽數(shù)量
              xAxis.setLabelCount(7);
              //設(shè)置數(shù)據(jù)格式
              xAxis.setValueFormatter(xAxisFormatter);
    
              IAxisValueFormatter custom = new MyAxisValueFormatter();
    
              YAxis leftAxis = mChart.getAxisLeft();
              leftAxis.setTypeface(mTfLight);
              leftAxis.setLabelCount(8, false);
              leftAxis.setValueFormatter(custom);
              leftAxis.setPosition(YAxisLabelPosition.OUTSIDE_CHART);
              //Sets the top axis space in percent of the full range. Default 10f
              leftAxis.setSpaceTop(15f);
              //設(shè)置Y軸最小的值
              leftAxis.setAxisMinimum(0f); // this replaces setStartAtZero(true)
    
              YAxis rightAxis = mChart.getAxisRight();
              rightAxis.setDrawGridLines(false);
              rightAxis.setTypeface(mTfLight);
              rightAxis.setLabelCount(8, false);
              rightAxis.setValueFormatter(custom);
              rightAxis.setSpaceTop(15f);
              rightAxis.setAxisMinimum(0f); // this replaces setStartAtZero(true)
              //設(shè)置圖例樣式蓖康,默認可以顯示,設(shè)置setEnabled(false)垒手;可以不繪制
              Legend l = mChart.getLegend();
              l.setVerticalAlignment(Legend.LegendVerticalAlignment.BOTTOM);
              l.setHorizontalAlignment(Legend.LegendHorizontalAlignment.LEFT);
              l.setOrientation(Legend.LegendOrientation.HORIZONTAL);
              l.setDrawInside(false);
              l.setForm(LegendForm.SQUARE);
              l.setFormSize(9f);
              l.setTextSize(11f);
              l.setXEntrySpace(4f);
               //設(shè)置X軸和Y軸顯示的刻度
              private void setData(int count, float range) {
    
                     float start = 1f;
    
                      ArrayList<BarEntry> yVals1 = new ArrayList<BarEntry>();
    
                      for (int i = (int) start; i < start + count + 1; i++) {
                          float mult = (range + 1);
                          float val = (float) (Math.random() * mult);
                          yVals1.add(new BarEntry(i, val));
                      }
    
                      BarDataSet set1;
    
              if (mChart.getData() != null &&
              mChart.getData().getDataSetCount() > 0) {
                  set1 = (BarDataSet) mChart.getData().getDataSetByIndex(0);
                  set1.setValues(yVals1);
                  mChart.getData().notifyDataChanged();
                  mChart.notifyDataSetChanged();
              } else {
                  set1 = new BarDataSet(yVals1, "The year 2017");
                  set1.setColors(ColorTemplate.MATERIAL_COLORS);
    
                  ArrayList<IBarDataSet> dataSets = new ArrayList<IBarDataSet>();
                  dataSets.add(set1);
    
                  BarData data = new BarData(dataSets);
                  data.setValueTextSize(10f);
                  data.setValueTypeface(mTfLight);
                  data.setBarWidth(0.9f);
    
                  mChart.setData(data);
              }
          }
    

折線圖

效果圖
zxt.png
  • 在XML中加入如下代碼

      <com.github.mikephil.charting.charts.LineChart
              android:id="@+id/chart"
              android:layout_width="match_parent"
              android:layout_height="200dp" />
    
  • 主要代碼以及數(shù)據(jù)的設(shè)置

      xVals = new ArrayList<>();
      yVals = new ArrayList<>();
      random = new Random();//產(chǎn)生隨機數(shù)字
    
      for(int i = 0 ; i<12; i++) {
          float x = random.nextInt(10000);//獲取value值
          yVals.add(new Entry(x, i));//創(chuàng)建Entry并且添加到Y(jié)值的list中蒜焊,Y軸的值,一個entry代表一個顯示的值
          xVals.add( (i+1) + "月");//橫坐標顯示xxx月
      }
    
      dataSet = new LineDataSet(yVals, "金額");//創(chuàng)建數(shù)據(jù)集并設(shè)置標簽
    
      dataSet.setColors(ColorTemplate.COLORFUL_COLORS);//設(shè)置數(shù)據(jù)集顯示的顏色科贬,預(yù)支顏色模版ColorTemplate泳梆,也可以設(shè)置單一顏色和colors
    
      dataSet.setHighlightEnabled(true);//設(shè)置高亮
      dataSet.setValueTextColor(Color.BLUE);//設(shè)置Value值的顯示文字顏色,字體大小和字體種類榜掌,這里我沒有添加對應(yīng)字體可以自己修改
    
      dataSet.setValueTextSize(10.0f);
      dataSet.setValueTypeface(null);
    
      data = new LineData(xVals, dataSet);//創(chuàng)建LineData,x軸List和Y軸數(shù)據(jù)集為參數(shù)
    
      chart.setData(data);//給圖表添加數(shù)據(jù)
      chart.setDescription("收支狀態(tài)");//設(shè)置圖表描述的內(nèi)容位置优妙,字體等等
      chart.setDescriptionColor(Color.YELLOW);
      chart.setDescriptionTextSize(15f);
      chart.setDescriptionPosition(540, 40);
    
      chart.getXAxis().setPosition(XAxisPosition.BOTTOM);//設(shè)置X軸的顯示位置,通過XAxisPosition枚舉類型來設(shè)置
      chart.getXAxis().setAxisMinValue(0.0f);//設(shè)置X軸的最小值
      chart.getAxisRight().setEnabled(false);//關(guān)閉右邊的Y軸憎账,因為默認有兩條套硼,左邊一條,右邊一條胞皱,MPAndroidChart中有        setEnabled方法的元素基本上都是使能的作用
      chart.animateY(3000);//動畫效果邪意,MPAndroidChart中還有很多動畫效果可以挖掘
    
      //當值被選中的時候,執(zhí)行操作顯示一個Toast
      chart.setOnChartValueSelectedListener(new OnChartValueSelectedListener() {
    
                  @Override
                  public void onValueSelected(Entry e, int dataSetIndex, Highlight h) {
                      // TODO Auto-generated method stub
                      Toast.makeText(MainActivity.this, String.valueOf(e.getVal()), Toast.LENGTH_SHORT).show();
                  }
    
                  @Override
                  public void onNothingSelected() {
                      // TODO Auto-generated method stub
    
                  }
              });
    
  • 基本屬性

      //創(chuàng)建描述信息
      Description description =new Description();
      description.setText("測試圖表");
      description.setTextColor(Color.RED);
      description.setTextSize(20);
      lineChart.setDescription(description);//設(shè)置圖表描述信息
      lineChart.setNoDataText("沒有數(shù)據(jù)熬");//沒有數(shù)據(jù)時顯示的文字
      lineChart.setNoDataTextColor(Color.BLUE);//沒有數(shù)據(jù)時顯示文字的顏色
      lineChart.setDrawGridBackground(false);//chart 繪圖區(qū)后面的背景矩形將繪制
      lineChart.setDrawBorders(false);//禁止繪制圖表邊框的線
      //lineChart.setBorderColor(); //設(shè)置 chart 邊框線的顏色反砌。
      //lineChart.setBorderWidth(); //設(shè)置 chart 邊界線的寬度雾鬼,單位 dp。
      //lineChart.setLogEnabled(true);//打印日志
      //lineChart.notifyDataSetChanged();//刷新數(shù)據(jù)
      //lineChart.invalidate();//重繪
    
    
    
             //獲取此圖表的x軸宴树,設(shè)置x軸效果
              XAxis xAxis = lineChart.getXAxis();
              xAxis.setEnabled(true);//設(shè)置軸啟用或禁用 如果禁用以下的設(shè)置全部不生效
              xAxis.setDrawAxisLine(true);//是否繪制軸線
              xAxis.setDrawGridLines(true);//設(shè)置x軸上每個點對應(yīng)的線
              xAxis.setDrawLabels(true);//繪制標簽  指x軸上的對應(yīng)數(shù)值
              xAxis.setPosition(XAxis.XAxisPosition.BOTTOM);//設(shè)置x軸的顯示位置
              //xAxis.setTextSize(20f);//設(shè)置字體
              //xAxis.setTextColor(Color.BLACK);//設(shè)置字體顏色
              //設(shè)置豎線的顯示樣式為虛線
              //lineLength控制虛線段的長度
              //spaceLength控制線之間的空間
              xAxis.enableGridDashedLine(10f, 10f, 0f);
              //xAxis.setAxisMinimum(0f);//設(shè)置x軸的最小值
              // xAxis.setAxisMaximum(10f);//設(shè)置最大值
              xAxis.setAvoidFirstLastClipping(true);//圖表將避免第一個和最后一個標簽條目被減掉在圖表或屏幕的邊緣
              xAxis.setLabelRotationAngle(10f);//設(shè)置x軸標簽的旋轉(zhuǎn)角度
              // 設(shè)置x軸顯示標簽數(shù)量  還有一個重載方法第二個參數(shù)為布爾值強制設(shè)置數(shù)量 如果啟用會導(dǎo)致繪制點出現(xiàn)偏差
              // xAxis.setLabelCount(10);
              // xAxis.setTextColor(Color.BLUE);//設(shè)置軸標簽的顏色
              // xAxis.setTextSize(24f);//設(shè)置軸標簽的大小
              // xAxis.setGridLineWidth(10f);//設(shè)置豎線大小
              // xAxis.setGridColor(Color.RED);//設(shè)置豎線顏色
              // xAxis.setAxisLineColor(Color.GREEN);//設(shè)置x軸線顏色
              // xAxis.setAxisLineWidth(5f);//設(shè)置x軸線寬度
              // xAxis.setValueFormatter();//格式化x軸標簽顯示字符
    
    
    
            /**
             * Y軸默認顯示左右兩個軸線
             */
             //獲取右邊的軸線
              YAxis rightAxis=lineChart.getAxisRight();
             //設(shè)置圖表右邊的y軸禁用
             rightAxis.setEnabled(false);
             //獲取左邊的軸線
             YAxis leftAxis = lineChart.getAxisLeft();
             //設(shè)置網(wǎng)格線為虛線效果
             leftAxis.enableGridDashedLine(10f, 10f, 0f);
             //是否繪制0所在的網(wǎng)格線 
             leftAxis.setDrawZeroLine(false);
    
    
    
             //設(shè)置與圖表交互
             lineChart.setTouchEnabled(true); // 設(shè)置是否可以觸摸
             lineChart.setDragEnabled(true);// 是否可以拖拽
             lineChart.setScaleEnabled(false);// 是否可以縮放 x和y軸, 默認是true
             lineChart.setScaleXEnabled(true); //是否可以縮放 僅x軸
             lineChart.setScaleYEnabled(true); //是否可以縮放 僅y軸
             lineChart.setPinchZoom(true);  //設(shè)置x軸和y軸能否同時縮放策菜。默認是否
             lineChart.setDoubleTapToZoomEnabled(true);//設(shè)置是否可以通過雙擊屏幕放大圖表。默認是true
             lineChart.setHighlightPerDragEnabled(true);//能否拖拽高亮線(數(shù)據(jù)點與坐標的提示線)酒贬,默認是true
             lineChart.setDragDecelerationEnabled(true);//拖拽滾動時又憨,手放開是否會持續(xù)滾動,默認是true(false是拖到哪是哪锭吨,true拖拽之后還會有緩沖)
             lineChart.setDragDecelerationFrictionCoef(0.99f);//與上面那個屬性配合竟块,持續(xù)滾動時的速度快慢,[0,1) 0代表立即停止耐齐。
    
zxta.png

餅狀圖

效果圖
bzt.png
  • 在XML中加入如下代碼

      <com.github.mikephil.charting.charts.PieChart
              android:id="@+id/chart1"
              android:layout_width="match_parent"
              android:layout_height="300dp"
      />
    
  • 主要代碼以及數(shù)據(jù)的設(shè)置

      public class HalfPieChartActivity extends DemoBase {
    
          private PieChart mChart;
    
          @Override
          protected void onCreate(Bundle savedInstanceState) {
              super.onCreate(savedInstanceState);
              getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
              WindowManager.LayoutParams.FLAG_FULLSCREEN);
              setContentView(R.layout.activity_piechart_half);
    
              mChart = (PieChart) findViewById(R.id.chart1);
              mChart.setBackgroundColor(Color.WHITE);
    
              moveOffScreen();
    
              mChart.setUsePercentValues(true);
              mChart.getDescription().setEnabled(false);
    
              mChart.setCenterTextTypeface(mTfLight);
              mChart.setCenterText(generateCenterSpannableText());
    
              mChart.setDrawHoleEnabled(true);
              mChart.setHoleColor(Color.WHITE);
    
              mChart.setTransparentCircleColor(Color.WHITE);
              mChart.setTransparentCircleAlpha(110);
    
              mChart.setHoleRadius(58f);
              mChart.setTransparentCircleRadius(61f);
      
              mChart.setDrawCenterText(true);
    
              mChart.setRotationEnabled(false);
              mChart.setHighlightPerTapEnabled(true);
    
              mChart.setMaxAngle(360f); // HALF CHART
              mChart.setRotationAngle(180f);
              mChart.setCenterTextOffset(0, -20);
    
              setData(4, 100);
    
              mChart.animateY(1400, Easing.EasingOption.EaseInOutQuad);
    
              Legend l = mChart.getLegend();
              l.setVerticalAlignment(Legend.LegendVerticalAlignment.TOP);
              l.setHorizontalAlignment(Legend.LegendHorizontalAlignment.CENTER);
              l.setOrientation(Legend.LegendOrientation.HORIZONTAL);
              l.setDrawInside(false);
              l.setXEntrySpace(7f);
              l.setYEntrySpace(0f);
              l.setYOffset(0f);
    
              // entry label styling
              mChart.setEntryLabelColor(Color.WHITE);
              mChart.setEntryLabelTypeface(mTfRegular);
              mChart.setEntryLabelTextSize(12f);
          }
    
          private void setData(int count, float range) {
    
              ArrayList<PieEntry> values = new ArrayList<PieEntry>();
    
              for (int i = 0; i < count; i++) {
                  values.add(new PieEntry((float) ((Math.random() * range) + range / 5), mParties[i % mParties.length]));
              }
    
              PieDataSet dataSet = new PieDataSet(values, "Election Results");
              dataSet.setSliceSpace(3f);
              dataSet.setSelectionShift(5f);
    
              dataSet.setColors(ColorTemplate.MATERIAL_COLORS);
              //dataSet.setSelectionShift(0f);
    
              PieData data = new PieData(dataSet);
              data.setValueFormatter(new PercentFormatter());
              data.setValueTextSize(11f);
              data.setValueTextColor(Color.WHITE);
              data.setValueTypeface(mTfLight);
              mChart.setData(data);
    
              mChart.invalidate();
          }
    
          private SpannableString generateCenterSpannableText() {
    
              SpannableString s = new SpannableString("MPAndroidChart\ndeveloped by Philipp Jahoda");
              s.setSpan(new RelativeSizeSpan(1.7f), 0, 14, 0);
              s.setSpan(new StyleSpan(Typeface.NORMAL), 14, s.length() - 15, 0);
              s.setSpan(new ForegroundColorSpan(Color.GRAY), 14, s.length() - 15, 0);
              s.setSpan(new RelativeSizeSpan(.8f), 14, s.length() - 15, 0);
              s.setSpan(new StyleSpan(Typeface.ITALIC), s.length() - 14, s.length(), 0);
              s.setSpan(new ForegroundColorSpan(ColorTemplate.getHoloBlue()), s.length() - 14, s.length(), 0);
              return s;
          }
    
          private void moveOffScreen() {
    
              Display display = getWindowManager().getDefaultDisplay();
              int height = display.getHeight();  // deprecated
    
              int offset = (int)(height * 0.65); /* percent to move */
    
              RelativeLayout.LayoutParams rlParams =
              (RelativeLayout.LayoutParams)mChart.getLayoutParams();
              rlParams.setMargins(0, 0, 0, -offset);
              mChart.setLayoutParams(rlParams);
          }
      }
    
  • 基本屬性

      // 設(shè)置 pieChart 圖表基本屬性
      mChart.setUsePercentValues(false);            //使用百分比顯示
      mChart.getDescription().setEnabled(false);    //設(shè)置pieChart圖表的描述
      mChart.setBackgroundColor(Color.YELLOW);      //設(shè)置pieChart圖表背景色
      mChart.setExtraOffsets(5, 10, 60, 10);        //設(shè)置pieChart圖表上下左右的偏移,類似于外邊距
      mChart.setDragDecelerationFrictionCoef(0.95f);//設(shè)置pieChart圖表轉(zhuǎn)動阻力摩擦系數(shù)[0,1]
      mChart.setRotationAngle(0);                   //設(shè)置pieChart圖表起始角度
      mChart.setRotationEnabled(true);              //設(shè)置pieChart圖表是否可以手動旋轉(zhuǎn)
      mChart.setHighlightPerTapEnabled(true);       //設(shè)置piecahrt圖表點擊Item高亮是否可用
      mChart.animateY(1400, Easing.EasingOption.EaseInOutQuad);// 設(shè)置pieChart圖表展示動畫效果
    
      // 設(shè)置 pieChart 圖表Item文本屬性
      mChart.setDrawEntryLabels(true);              //設(shè)置pieChart是否只顯示餅圖上百分比不顯示文字(true:下面屬性才有效果)
      mChart.setEntryLabelColor(Color.WHITE);       //設(shè)置pieChart圖表文本字體顏色
      mChart.setEntryLabelTypeface(mTfRegular);     //設(shè)置pieChart圖表文本字體樣式
      mChart.setEntryLabelTextSize(10f);            //設(shè)置pieChart圖表文本字體大小
    
      // 設(shè)置 pieChart 內(nèi)部圓環(huán)屬性
      mChart.setDrawHoleEnabled(true);              //是否顯示PieChart內(nèi)部圓環(huán)(true:下面屬性才有意義)
      mChart.setHoleRadius(28f);                    //設(shè)置PieChart內(nèi)部圓的半徑(這里設(shè)置28.0f)
      mChart.setTransparentCircleRadius(31f);       //設(shè)置PieChart內(nèi)部透明圓的半徑(這里設(shè)置31.0f)
      mChart.setTransparentCircleColor(Color.BLACK);//設(shè)置PieChart內(nèi)部透明圓與內(nèi)部圓間距(31f-28f)填充顏色
      mChart.setTransparentCircleAlpha(50);         //設(shè)置PieChart內(nèi)部透明圓與內(nèi)部圓間距(31f-28f)透明度[0~255]數(shù)值越小越透明
      mChart.setHoleColor(Color.WHITE);             //設(shè)置PieChart內(nèi)部圓的顏色
      mChart.setDrawCenterText(true);               //是否繪制PieChart內(nèi)部中心文本(true:下面屬性才有意義)
      mChart.setCenterTextTypeface(mTfLight);       //設(shè)置PieChart內(nèi)部圓文字的字體樣式
      mChart.setCenterText("Test");                 //設(shè)置PieChart內(nèi)部圓文字的內(nèi)容
      mChart.setCenterTextSize(10f);                //設(shè)置PieChart內(nèi)部圓文字的大小
      mChart.setCenterTextColor(Color.RED);         //設(shè)置PieChart內(nèi)部圓文字的顏色
    
      // pieChart添加數(shù)據(jù)
      setData();
    
      // 獲取pieCahrt圖列
      Legend l = mChart.getLegend();
      l.setEnabled(true);                    //是否啟用圖列(true:下面屬性才有意義)
      l.setVerticalAlignment(Legend.LegendVerticalAlignment.TOP);  
      l.setHorizontalAlignment(Legend.LegendHorizontalAlignment.RIGHT);
      l.setOrientation(Legend.LegendOrientation.VERTICAL);
      l.setForm(Legend.LegendForm.DEFAULT); //設(shè)置圖例的形狀
      l.setFormSize(10);                    //設(shè)置圖例的大小
      l.setFormToTextSpace(10f);            //設(shè)置每個圖例實體中標簽和形狀之間的間距
      l.setDrawInside(false);
      l.setWordWrapEnabled(true);           //設(shè)置圖列換行(注意使用影響性能,僅適用legend位于圖表下面)
      l.setXEntrySpace(10f);                //設(shè)置圖例實體之間延X軸的間距(setOrientation = HORIZONTAL有效)
      l.setYEntrySpace(8f);                 //設(shè)置圖例實體之間延Y軸的間距(setOrientation = VERTICAL 有效)
      l.setYOffset(0f);                     //設(shè)置比例塊Y軸偏移量
      l.setTextSize(14f);                   //設(shè)置圖例標簽文本的大小
      l.setTextColor(Color.parseColor("#ff9933"));//設(shè)置圖例標簽文本的顏色
    
      //pieChart 選擇監(jiān)聽
      mChart.setOnChartValueSelectedListener(this);
    
      //設(shè)置MARKERVIEW
      CustomMarkerView mv = new CustomMarkerView(this, new PercentFormatter());
      mv.setChartView(mChart);
      mChart.setMarker(mv);
    
      /**
        * 設(shè)置餅圖的數(shù)據(jù)
        */
      private void setData() {
          ArrayList<PieEntry> pieEntryList = new ArrayList<PieEntry>();
          ArrayList<Integer> colors = new ArrayList<Integer>();
          colors.add(Color.parseColor("#f17548"));
          colors.add(Color.parseColor("#FF9933"));
          //餅圖實體 PieEntry
          PieEntry CashBalance = new PieEntry(70, "現(xiàn)金余額 1500");
          PieEntry ConsumptionBalance = new PieEntry(30, "消費余額 768");
          pieEntryList.add(CashBalance);
          pieEntryList.add(ConsumptionBalance);
          //餅狀圖數(shù)據(jù)集 PieDataSet
          PieDataSet pieDataSet = new PieDataSet(pieEntryList, "資產(chǎn)總覽");
          pieDataSet.setSliceSpace(3f);           //設(shè)置餅狀I(lǐng)tem之間的間隙
          pieDataSet.setSelectionShift(10f);      //設(shè)置餅狀I(lǐng)tem被選中時變化的距離
          pieDataSet.setColors(colors);           //為DataSet中的數(shù)據(jù)匹配上顏色集(餅圖Item顏色)
          //最終數(shù)據(jù) PieData
          PieData pieData = new PieData(pieDataSet);
          pieData.setDrawValues(true);            //設(shè)置是否顯示數(shù)據(jù)實體(百分比,true:以下屬性才有意義)
          pieData.setValueTextColor(Color.BLUE);  //設(shè)置所有DataSet內(nèi)數(shù)據(jù)實體(百分比)的文本顏色
          pieData.setValueTextSize(12f);          //設(shè)置所有DataSet內(nèi)數(shù)據(jù)實體(百分比)的文本字體大小
          pieData.setValueTypeface(mTfLight);     //設(shè)置所有DataSet內(nèi)數(shù)據(jù)實體(百分比)的文本字體樣式
          pieData.setValueFormatter(new PercentFormatter());//設(shè)置所有DataSet內(nèi)數(shù)據(jù)實體(百分比)的文本字體格式
          mChart.setData(pieData);
          mChart.highlightValues(null);
          mChart.invalidate();                    //將圖表重繪以顯示設(shè)置的屬性和數(shù)據(jù)
      }
    
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末埠况,一起剝皮案震驚了整個濱河市耸携,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌辕翰,老刑警劉巖夺衍,帶你破解...
    沈念sama閱讀 222,000評論 6 515
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異喜命,居然都是意外死亡沟沙,警方通過查閱死者的電腦和手機,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 94,745評論 3 399
  • 文/潘曉璐 我一進店門壁榕,熙熙樓的掌柜王于貴愁眉苦臉地迎上來矛紫,“玉大人,你說我怎么就攤上這事牌里〖找В” “怎么了?”我有些...
    開封第一講書人閱讀 168,561評論 0 360
  • 文/不壞的土叔 我叫張陵牡辽,是天一觀的道長喳篇。 經(jīng)常有香客問我,道長态辛,這世上最難降的妖魔是什么麸澜? 我笑而不...
    開封第一講書人閱讀 59,782評論 1 298
  • 正文 為了忘掉前任,我火速辦了婚禮奏黑,結(jié)果婚禮上炊邦,老公的妹妹穿的比我還像新娘。我一直安慰自己攀涵,他們只是感情好铣耘,可當我...
    茶點故事閱讀 68,798評論 6 397
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著以故,像睡著了一般蜗细。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上怒详,一...
    開封第一講書人閱讀 52,394評論 1 310
  • 那天炉媒,我揣著相機與錄音,去河邊找鬼昆烁。 笑死吊骤,一個胖子當著我的面吹牛,可吹牛的內(nèi)容都是我干的静尼。 我是一名探鬼主播白粉,決...
    沈念sama閱讀 40,952評論 3 421
  • 文/蒼蘭香墨 我猛地睜開眼传泊,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了鸭巴?” 一聲冷哼從身側(cè)響起眷细,我...
    開封第一講書人閱讀 39,852評論 0 276
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎鹃祖,沒想到半個月后溪椎,有當?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 46,409評論 1 318
  • 正文 獨居荒郊野嶺守林人離奇死亡恬口,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 38,483評論 3 341
  • 正文 我和宋清朗相戀三年校读,在試婚紗的時候發(fā)現(xiàn)自己被綠了。 大學時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片祖能。...
    茶點故事閱讀 40,615評論 1 352
  • 序言:一個原本活蹦亂跳的男人離奇死亡歉秫,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出芯杀,到底是詐尸還是另有隱情端考,我是刑警寧澤,帶...
    沈念sama閱讀 36,303評論 5 350
  • 正文 年R本政府宣布揭厚,位于F島的核電站却特,受9級特大地震影響,放射性物質(zhì)發(fā)生泄漏筛圆。R本人自食惡果不足惜裂明,卻給世界環(huán)境...
    茶點故事閱讀 41,979評論 3 334
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望太援。 院中可真熱鬧闽晦,春花似錦、人聲如沸提岔。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,470評論 0 24
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽碱蒙。三九已至荠瘪,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間赛惩,已是汗流浹背哀墓。 一陣腳步聲響...
    開封第一講書人閱讀 33,571評論 1 272
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留喷兼,地道東北人篮绰。 一個月前我還...
    沈念sama閱讀 49,041評論 3 377
  • 正文 我出身青樓,卻偏偏與公主長得像季惯,于是被迫代替她去往敵國和親吠各。 傳聞我的和親對象是個殘疾皇子臀突,可洞房花燭夜當晚...
    茶點故事閱讀 45,630評論 2 359

推薦閱讀更多精彩內(nèi)容

  • 開始 ####安裝 為了使用 LineChart, BarChart, ScatterChart, CandleS...
    帥氣的豬豬閱讀 8,468評論 0 1
  • Fastlane是一套使用Ruby寫的自動化工具集,用于iOS和Android的自動化打包走孽、發(fā)布等工作惧辈,可以節(jié)省大...
    刃之劍閱讀 230評論 0 0
  • Opengl ES( Opengl for Embedded Systems)是 Opengl三維圖形API的子集...
    搜捕兒閱讀 469評論 0 0
  • 一,HTML語言的一般語法: 1磕瓷,圍堵標記:<>… 1)帶屬性的標記: … 2)無屬性的標記:加粗 居中 標題 2...
    清水易藍閱讀 1,267評論 0 2
  • 本來下午是要帶寶寶去上水浴課的,結(jié)果寶寶一覺睡過了念逞,就改了時間困食。于是帶寶寶去繪本館溜達一圈◆岢校總結(jié)上次的借書經(jīng)驗硕盹。我...
    大果果ly閱讀 145評論 0 0