实现柱状图与条形图的结合,MPAndroidChart 的简单使用

2196231334 8年前
   <pre>  <code class="language-java">先贴效果图:</code></pre>    <pre>  <code class="language-java">这种样式的统计表格也是比较常用的,下面直接贴代码:</code></pre>    <pre>  <code class="language-java">public class ChartActivity extends BaseActivity {      @BindView(R.id.<em>chart1</em>)      MyCombinedChart mChart1;//完成情况      private final int itemcount = 3;      protected String[] mMonths = new String[]{"张三", "李四", "王五"};//X轴标签        private List<Float> lineDatas;//线图数据源      private List<float[]> barDatas;//堆图数据源        @Override      public void init(Bundle savedInstanceState) {          setContentView(R.layout.<em>activity_chart</em>,this);          initTitleBar(R.id.<em>title</em>,"报表");          setChart1();      }        <em>/** </em><em> * 配置维修单完成情况 </em><em> */ </em><em> </em>private void setChart1() {          configChart(mChart1);      }        private void configChart(MyCombinedChart mChart){          mChart.setDrawValueAboveBar(false);          mChart.getDescription().setEnabled(false);//不显示表名  //        mChart.getDescription().setPosition();//设置表名在屏幕中的位置          mChart.setBackgroundColor(Color.<em>WHITE</em>);          mChart.setDrawGridBackground(false);          mChart.setDrawBarShadow(false);          mChart.setScaleYEnabled(false);//Y轴方向上不允许拉伸          mChart.setHighlightFullBarEnabled(false);            // draw bars behind lines设置绘制顺序,重叠部分的图案后绘制的会遮挡先绘制的          mChart.setDrawOrder(new CombinedChart.DrawOrder[]{                  CombinedChart.DrawOrder.<em>BAR</em>, CombinedChart.DrawOrder.<em>LINE </em><em> </em>});            //图例          Legend l = mChart.getLegend();          l.setWordWrapEnabled(true);          l.setVerticalAlignment(Legend.LegendVerticalAlignment.<em>BOTTOM</em>);          l.setHorizontalAlignment(Legend.LegendHorizontalAlignment.<em>CENTER</em>);          l.setOrientation(Legend.LegendOrientation.<em>HORIZONTAL</em>);          l.setDrawInside(false);              //设置右边Y轴标签          YAxis rightAxis = mChart.getAxisRight();          rightAxis.setAxisMaximum(100);//设置最大数值          rightAxis.setLabelCount(6, true);//设置标签数量          rightAxis.setValueFormatter(new MyAxisValueFormatter());//设置数值显示格式          rightAxis.setDrawGridLines(true);//绘制网格线          rightAxis.setAxisMinimum(0f); // this replaces setStartAtZero(true)          //设置左边Y轴标签          YAxis leftAxis = mChart.getAxisLeft();          leftAxis.setAxisMaximum(20);          leftAxis.setLabelCount(6, true);          leftAxis.setDrawGridLines(true);          leftAxis.setAxisMinimum(0f); // this replaces setStartAtZero(true)          //设置X轴标签          XAxis xAxis = mChart.getXAxis();          xAxis.setPosition(XAxis.XAxisPosition.<em>BOTTOM</em>);          xAxis.setAxisMinimum(0f);          xAxis.setGranularity(1f);          xAxis.setDrawGridLines(false);          xAxis.setValueFormatter(new IAxisValueFormatter() {              @Override              public String getFormattedValue(float value, AxisBase axis) {                  if (value==0||value==mMonths.length+1){                      return "";                  }                  return mMonths[(int) (value-1) % mMonths.length];              }                @Override              public int getDecimalDigits() {                  return 0;              }          });            CombinedData data = new CombinedData();            data.setData(generateBarData());          data.setData(generateLineData());          //设置字体样式  //        data.setValueTypeface(mTfLight);            xAxis.setAxisMaximum(data.getXMax() + 1);//最大宽度另加1个单元格的宽度            mChart.setData(data);          mChart.invalidate();      }        private LineData generateLineData() {          lineDatas = new ArrayList<>();          for (int i = 0; i < barDatas.size(); i++) {                lineDatas.add(barDatas.get(i)[0] / (plus(barDatas.get(i))) * 100);            }            LineData d = new LineData();            ArrayList<Entry> entries = new ArrayList<Entry>();            //传入数据          for (int index = 0; index < itemcount; index++)              entries.add(new Entry(index + 1, lineDatas.get(index)));            LineDataSet set = new LineDataSet(entries, "完成率");          set.setColor(getResources().getColor(R.color.<em>chart_green</em>));          set.setLineWidth(2.5f);          set.setCircleColor(Color.<em>rgb(240, 238, 70)); set.setCircleRadius(5f); set.setFillColor(Color.<em>rgb(240, 238, 70)); set.setMode(LineDataSet.Mode.<em>LINEAR</em>); set.setDrawValues(true); set.setValueTextSize(10f); set.setValueTextColor(getResources().getColor(R.color.<em>black</em>));//设置内容字体颜色 set.setAxisDependency(YAxis.AxisDependency.<em>RIGHT</em>);//以右边Y轴的标签绘制 d.addDataSet(set); MyValueFormatter format = new MyValueFormatter(); d.setValueFormatter(format); return d; } private float plus(float[] f) { float plus = 0; for (float aF : f) { plus += aF; } return plus; } private BarData generateBarData() { barDatas = new ArrayList<>(); barDatas.add(new float[]{6, 8}); barDatas.add(new float[]{15, 4}); barDatas.add(new float[]{11, 7}); ArrayList<BarEntry> entries2 = new ArrayList<>(); for (int index = 0; index < itemcount; index++) { // stacked entries2.add(new BarEntry(index + 1, barDatas.get(index))); } BarDataSet set2 = new BarDataSet(entries2, ""); set2.setStackLabels(new String[]{"已完成", "未完成"}); set2.setColors(getResources().getColor(R.color.<em>chart_blue</em>),getResources().getColor(R.color.<em>chart_red</em>)); set2.setValueTextColor(getResources().getColor(R.color.<em>black</em>)); set2.setValueTextSize(10f); set2.setAxisDependency(YAxis.AxisDependency.<em>LEFT</em>);//以左边Y轴的标签绘制 float barWidth = 0.45f; // x2 dataset BarData d = new BarData(set2); d.setBarWidth(barWidth); return d; }</em></em></code></pre>    <pre>  <code class="language-java">class MyAxisValueFormatter implements IAxisValueFormatter  {        private DecimalFormat mFormat;        public MyAxisValueFormatter() {          mFormat = new DecimalFormat("###,###,###,##0.0");      }        @Override      public String getFormattedValue(float value, AxisBase axis) {          return mFormat.format(value) + "%";      }          //小数点后数字个数      @Override      public int getDecimalDigits() {          return 0;      }  }</code></pre>    <pre>  <code class="language-java">class MyValueFormatter implements IValueFormatter  {        private DecimalFormat mFormat;          public MyValueFormatter() {          mFormat = new DecimalFormat("###,###,###,##0.0");      }        @Override      public String getFormattedValue(float value, Entry entry, int dataSetIndex, ViewPortHandler viewPortHandler) {          //百分比显示          return mFormat.format(value)+ "%" ;      }    }</code></pre>    <pre>  <code class="language-java">class MyYAxis extends YAxis {          public MyYAxis() {          super();      }        public MyYAxis(AxisDependency position) {          super(position);      }        @Override      public String getFormattedLabel(int index) {          if (index < 0 || index >= mEntries.length)              return "";          else {              float max=mEntries[0];              for (int i=1;i<mEntries.length;i++){                  Log.d("test", "getFormattedLabel: "+mEntries[i]);                  if (mEntries[i]>max){                      max=mEntries[i];                  }              }              return getValueFormatter().getFormattedValue(mEntries[index] /max*100, this);          }      }      }</code></pre>    <p>}</p>    <pre>  <code class="language-java">public class MyCombinedChart extends CombinedChart {      public MyCombinedChart(Context context) {          super(context);      }        public MyCombinedChart(Context context, AttributeSet attrs) {          super(context, attrs);      }        public MyCombinedChart(Context context, AttributeSet attrs, int defStyle) {          super(context, attrs, defStyle);      }        @Override      public YAxis getAxisRight() {          return super.getAxisRight();      }        @Override      protected void init() {          super.init();            mAxisLeft = new YAxis(YAxis.AxisDependency.<em>LEFT</em>);          mAxisRight = new MyYAxis(MyYAxis.AxisDependency.<em>RIGHT</em>);            mLeftAxisTransformer = new Transformer(mViewPortHandler);          mRightAxisTransformer = new Transformer(mViewPortHandler);            mAxisRendererLeft = new YAxisRenderer(mViewPortHandler, mAxisLeft, mLeftAxisTransformer);          mAxisRendererRight = new YAxisRenderer(mViewPortHandler, mAxisRight, mRightAxisTransformer);            mXAxisRenderer = new XAxisRenderer(mViewPortHandler, mXAxis, mLeftAxisTransformer);            setHighlighter(new ChartHighlighter(this));            mChartTouchListener = new BarLineChartTouchListener(this, mViewPortHandler.getMatrixTouch(), 3f);            mGridBackgroundPaint = new Paint();          mGridBackgroundPaint.setStyle(Paint.Style.<em>FILL</em>);          // mGridBackgroundPaint.setColor(Color.WHITE);          mGridBackgroundPaint.setColor(Color.<em>rgb(240, 240, 240)); // light // grey mBorderPaint = new Paint(); mBorderPaint.setStyle(Paint.Style.<em>STROKE</em>); mBorderPaint.setColor(Color.<em>BLACK</em>); mBorderPaint.setStrokeWidth(Utils.<em>convertDpToPixel(1f)); } }</em></em></code></pre>    <p> </p>    <p>来自:http://blog.csdn.net/dovar_66/article/details/53063420</p>    <p> </p>