目录
一、MPAndroidChart概述
二、案例运行效果
1、主控界面
2、显示饼状图
3、显示柱状图
4、显示折线图
5、显示动态折线图
三、项目结构图
1、Project视图
2、Android视图
四、实现步骤
1、app的build.gradle里添加依赖
2、主控界面
(1)布局activity_main.xml
(2)主界面类MainActivity
3、显示饼状图
(1)布局activity_pie_chart.xml
(2)饼图界面类PieChartActivity
4、显示柱状图
(1)布局activity_bar_chart.xml
(2)柱状图界面类BarChartActivity
5、显示折线图
(1)布局activity_line_chart.xml
(2)折线图界面类LineChartActivity
6、显示动态折线图
(1)布局activity_dynamic_line_chart.xml
(2)动态折线图界面类DynamicLineChartActivity
MPAndroidChart是一款优秀的开源图表插件。
GitHub网址:https://github.com/PhilJay/MPAndroidChart
今天学习三种类型的图表:饼状图、柱状图和折线图
两个jar包下载链接:https://pan.baidu.com/s/1quvSQuq-HaCc2vsFJ3IKxw 提取码:t4rb
package net.hw.mpchart;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void showPieChart(View view) {
startActivity(new Intent(MainActivity.this, PieChartActivity.class));
}
public void showBarChart(View view) {
startActivity(new Intent(MainActivity.this, BarChartActivity.class));
}
public void showLineChart(View view) {
startActivity(new Intent(MainActivity.this, LineChartActivity.class));
}
public void showDynamicLineChart(View view) {
startActivity(new Intent(MainActivity.this, DynamicLineChartActivity.class));
}
}
package net.hw.mpchart;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.DisplayMetrics;
import com.github.mikephil.charting.charts.PieChart;
import com.github.mikephil.charting.components.Legend;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.data.PieData;
import com.github.mikephil.charting.data.PieDataSet;
import java.util.ArrayList;
public class PieChartActivity extends AppCompatActivity {
private PieChart mChart;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_pie_chart);
mChart = (PieChart) findViewById(R.id.chart);
showChart(getPieData());
}
private void showChart(PieData pieData) {
mChart.setHoleColorTransparent(true);
mChart.setHoleRadius(60f); //内环半径
mChart.setTransparentCircleRadius(64f); // 半透明圈半径
// mChart.setHoleRadius(0); // 实心圆
mChart.setDescription("测试饼状图");
mChart.setDrawCenterText(true); //饼状图中间可以添加文字
mChart.setCenterText("2017年季度收入"); //饼状图中间的文字
mChart.setDrawHoleEnabled(true);
mChart.setRotationAngle(90); // 初始旋转角度
mChart.setRotationEnabled(true); // 可以手动旋转
// mChart.setUsePercentValues(true); //显示成百分比
// 设置可触摸
mChart.setTouchEnabled(true);
// 设置数据
mChart.setData(pieData);
// 取消高亮显示
mChart.highlightValues(null);
mChart.invalidate();
Legend mLegend = mChart.getLegend(); //设置比例图
mLegend.setPosition(Legend.LegendPosition.RIGHT_OF_CHART); //最右边显示
mLegend.setForm(Legend.LegendForm.LINE); //设置比例图的形状,默认是方形
mLegend.setXEntrySpace(7f);
mLegend.setYEntrySpace(5f);
//设置动画
mChart.animateXY(1000, 1000);
}
private PieData getPieData() {
// xVals用来表示每个饼块上的文字
ArrayList xValues = new ArrayList();
for (int i = 0; i < 4; i++) {
xValues.add((i + 1) + "季度");
}
// yVals用来表示封装每个饼块的实际数据
ArrayList yValues = new ArrayList();
// 饼图数据
float quarterly1 = 456787;
float quarterly2 = 534283;
float quarterly3 = 345734;
float quarterly4 = 658465;
yValues.add(new Entry(quarterly1, 0));
yValues.add(new Entry(quarterly2, 1));
yValues.add(new Entry(quarterly3, 2));
yValues.add(new Entry(quarterly4, 3));
// y轴集合
PieDataSet pieDataSet = new PieDataSet(yValues, "2017年季度收入");
pieDataSet.setSliceSpace(0f); //设置个饼状图之间的距离
ArrayList colors = new ArrayList();
// 饼图颜色
colors.add(Color.rgb(205, 205, 205));
colors.add(Color.rgb(114, 188, 223));
colors.add(Color.rgb(255, 123, 124));
colors.add(Color.rgb(57, 135, 200));
// 设置饼图颜色
pieDataSet.setColors(colors);
// 设置选中态多出的长度
DisplayMetrics metrics = getResources().getDisplayMetrics();
float px = 5 * (metrics.densityDpi / 160f);
pieDataSet.setSelectionShift(px);
// 创建饼图数据
PieData pieData = new PieData(xValues, pieDataSet);
return pieData;
}
}
package net.hw.mpchart;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import com.github.mikephil.charting.charts.BarChart;
import com.github.mikephil.charting.data.BarData;
import com.github.mikephil.charting.data.BarDataSet;
import com.github.mikephil.charting.data.BarEntry;
import java.util.ArrayList;
public class BarChartActivity extends AppCompatActivity {
private BarChart mChart;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_bar_chart);
mChart = (BarChart) findViewById(R.id.chart);
showChart(getBarData());
}
/**
* 显示柱状图表
*
* @param barData
*/
private void showChart(BarData barData) {
// 设置描述
mChart.setDescription("测试柱状图");
// 设置可触摸
mChart.setTouchEnabled(true);
// 设置图表数据
mChart.setData(barData);
// 设置动画
mChart.animateY(1000);
}
/**
* 获取柱状数据
*
* @return
*/
private BarData getBarData() {
ArrayList xValues = new ArrayList();
for (int i = 0; i < 4; i++) {
xValues.add((i + 1) + "季度");
}
ArrayList yValues = new ArrayList();
float quarterly1 = 456787;
float quarterly2 = 534283;
float quarterly3 = 345734;
float quarterly4 = 658465;
yValues.add(new BarEntry(quarterly1, 0));
yValues.add(new BarEntry(quarterly2, 1));
yValues.add(new BarEntry(quarterly3, 2));
yValues.add(new BarEntry(quarterly4, 3));
BarDataSet barDataSet = new BarDataSet(yValues, "2017年季度收入");
ArrayList colors = new ArrayList();
colors.add(Color.rgb(205, 205, 205));
colors.add(Color.rgb(114, 188, 223));
colors.add(Color.rgb(255, 123, 124));
colors.add(Color.rgb(57, 135, 200));
barDataSet.setColors(colors);
BarData barData = new BarData(xValues, barDataSet);
return barData;
}
}
package net.hw.mpchart;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import com.github.mikephil.charting.charts.LineChart;
import com.github.mikephil.charting.components.YAxis;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.data.LineData;
import com.github.mikephil.charting.data.LineDataSet;
import com.github.mikephil.charting.utils.ColorTemplate;
import java.util.ArrayList;
public class LineChartActivity extends AppCompatActivity {
private LineChart mChart;
private boolean isRunning;
private Thread thread;
private Handler handler;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_line_chart);
mChart = (LineChart) findViewById(R.id.chart);
showChart(getLineData(12, 2000));
handler = new Handler() {
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
mChart.clear(); // 清空图表
showChart(getLineData(12, 2000));
}
};
}
private void showChart(LineData lineData) {
// 设置描述
mChart.setDescription("折线图演示");
// 设置触摸模式
mChart.setTouchEnabled(true);
// 设置图表数据
mChart.setData(lineData);
}
/**
* @param count 横向点个数
* @param range 纵向变化幅度
* @return
*/
private LineData getLineData(int count, float range) {
ArrayList xVals = new ArrayList();
for (int i = 0; i < count; i++) {
xVals.add((i + 1) + "月");
}
/
ArrayList yVals = new ArrayList();
for (int i = 0; i < count; i++) {
float mult = range / 2f;
float val = (float) (Math.random() * mult) + 1000;
yVals.add(new Entry(val, i));
}
// 创建数据集
LineDataSet set = new LineDataSet(yVals, "数据集");
set.setAxisDependency(YAxis.AxisDependency.LEFT);
set.setColor(ColorTemplate.getHoloBlue());
set.setCircleColor(Color.YELLOW);
set.setLineWidth(2f);
set.setCircleSize(3f);
set.setFillAlpha(65);
set.setFillColor(ColorTemplate.getHoloBlue());
set.setHighLightColor(Color.rgb(244, 117, 117));
set.setDrawCircleHole(false);
// 创建数据集列表
ArrayList dataSets = new ArrayList();
dataSets.add(set);
// 创建折线数据对象(第二个参数可以是set)
LineData lineData = new LineData(xVals, dataSets);
lineData.setValueTextColor(Color.BLACK);
lineData.setValueTextSize(9f);
return lineData;
}
public void doStart(View view) {
isRunning = true;
thread = new Thread(new Runnable() {
@Override
public void run() {
while (isRunning) {
try {
handler.sendEmptyMessage(0x001);
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
});
thread.start();
}
public void doStop(View view) {
isRunning = false;
thread = null;
}
}
package net.hw.mpchart;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import com.github.mikephil.charting.charts.LineChart;
import com.github.mikephil.charting.components.Legend;
import com.github.mikephil.charting.components.XAxis;
import com.github.mikephil.charting.components.YAxis;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.data.LineData;
import com.github.mikephil.charting.data.LineDataSet;
import com.github.mikephil.charting.formatter.ValueFormatter;
import com.github.mikephil.charting.utils.ColorTemplate;
import com.github.mikephil.charting.utils.ViewPortHandler;
import java.text.DecimalFormat;
public class DynamicLineChartActivity extends AppCompatActivity {
// 高温线下标
private final int HIGH = 0;
// 低温线下标
private final int LOW = 1;
private LineChart mChart;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_dynamic_line_chart);
mChart = (LineChart) findViewById(R.id.chart);
showChart(getLineData());
}
/**
* 显示图表
*/
private void showChart(LineData lineData) {
// 初始化图表
initChart();
// 数据显示的颜色
lineData.setValueTextColor(Color.BLACK);
// 给图表设置数据
mChart.setData(lineData);
}
/**
* 获取折线数据
*
* @return
*/
private LineData getLineData() {
// 创建折线数据
LineData lineData = new LineData();
// 添加数据集
lineData.addDataSet(getHighLineDataSet());
lineData.addDataSet(getLowLineDataSet());
// 返回折线数据
return lineData;
}
/**
* 初始化图表
*/
private void initChart() {
// 设置描述
mChart.setDescription("动态折线图");
// 设置可触摸
mChart.setTouchEnabled(true);
// 可拖曳
mChart.setDragEnabled(true);
// 可缩放
mChart.setScaleEnabled(true);
// 设置绘制网格背景
mChart.setDrawGridBackground(true);
mChart.setPinchZoom(true);
// 设置图表的背景颜色
mChart.setBackgroundColor(0xfff5f5f5);
// 图表注解(只有当数据集存在时候才生效)
Legend legend = mChart.getLegend();
// 设置图表注解部分的位置
legend.setPosition(Legend.LegendPosition.BELOW_CHART_CENTER);
// 线性,也可是圆
legend.setForm(Legend.LegendForm.LINE);
// 颜色
legend.setTextColor(Color.BLUE);
// x坐标轴
XAxis xl = mChart.getXAxis();
xl.setTextColor(0xff00897b);
xl.setDrawGridLines(false);
xl.setAvoidFirstLastClipping(true);
// 几个x坐标轴之间才绘制
xl.setSpaceBetweenLabels(5);
// 如果false,那么x坐标轴将不可见
xl.setEnabled(true);
// 将X坐标轴放置在底部,默认是在顶部。
xl.setPosition(XAxis.XAxisPosition.BOTTOM);
// 图表左边的y坐标轴线
YAxis leftAxis = mChart.getAxisLeft();
leftAxis.setTextColor(0xff37474f);
// 最大值
leftAxis.setAxisMaxValue(50f);
// 最小值
leftAxis.setAxisMinValue(-10f);
// 不一定要从0开始
leftAxis.setStartAtZero(false);
leftAxis.setDrawGridLines(true);
YAxis rightAxis = mChart.getAxisRight();
// 不显示图表的右边y坐标轴线
rightAxis.setEnabled(false);
}
// 为高温线和低温线添加一个坐标点
private void addChartEntry() {
// 获取图表数据
LineData lineData = mChart.getData();
// 添加横坐标值
lineData.addXValue((lineData.getXValCount()) + "");
// 增加高温
LineDataSet highLineDataSet = lineData.getDataSetByIndex(HIGH);
float high = (float) ((Math.random()) * 10 + 30);
Entry entryHigh = new Entry(high, highLineDataSet.getEntryCount());
lineData.addEntry(entryHigh, HIGH);
// 增加低温
LineDataSet lowLineDataSet = lineData.getDataSetByIndex(LOW);
float low = (float) ((Math.random()) * 10);
Entry entryLow = new Entry(low, lowLineDataSet.getEntryCount());
lineData.addEntry(entryLow, LOW);
// 使用新数据刷新图表
mChart.notifyDataSetChanged();
// 当前统计图表中最多在x轴坐标线上显示的总量
mChart.setVisibleXRangeMaximum(12);
mChart.moveViewToX(lineData.getXValCount() - 12);
}
// 初始化数据集,添加一条高温统计折线
private LineDataSet getHighLineDataSet() {
LineDataSet set = new LineDataSet(null, "高温");
set.setAxisDependency(YAxis.AxisDependency.LEFT);
// 折线的颜色
set.setColor(Color.RED);
set.setCircleColor(Color.YELLOW);
set.setLineWidth(2f);
set.setCircleSize(8f);
set.setFillAlpha(128);
set.setCircleColorHole(Color.BLUE);
set.setHighLightColor(Color.GREEN);
set.setValueTextColor(Color.RED);
set.setValueTextSize(10f);
set.setDrawValues(true);
set.setValueFormatter(new ValueFormatter() {
@Override
public String getFormattedValue(float value, Entry entry, int dataSetIndex,
ViewPortHandler viewPortHandler) {
DecimalFormat decimalFormat = new DecimalFormat(".0℃");
String s = "高温" + decimalFormat.format(value);
return s;
}
});
return set;
}
// 初始化数据集,添加一条低温统计折线
private LineDataSet getLowLineDataSet() {
LineDataSet set = new LineDataSet(null, "低温");
set.setAxisDependency(YAxis.AxisDependency.LEFT);
// 折线的颜色
set.setColor(ColorTemplate.getHoloBlue());
set.setCircleColor(Color.BLUE);
set.setLineWidth(2f);
set.setCircleSize(8f);
set.setFillAlpha(128);
set.setFillColor(ColorTemplate.getHoloBlue());
set.setHighLightColor(Color.DKGRAY);
set.setValueTextColor(Color.BLACK);
set.setCircleColorHole(Color.RED);
set.setValueTextSize(10f);
set.setDrawValues(true);
set.setValueFormatter(new ValueFormatter() {
@Override
public String getFormattedValue(float value, Entry entry, int dataSetIndex,
ViewPortHandler viewPortHandler) {
DecimalFormat decimalFormat = new DecimalFormat(".0℃");
String s = "低温" + decimalFormat.format(value);
return s;
}
});
return set;
}
/**
* 给图表添加数据
*
* @param view
*/
public void doStart(View view) {
addChartEntry();
}
}