Android 图表开源框架之MPAndroidChart LineChart折线图(一)
Android 图表开源框架之MPAndroidChart LineChart之常用自定义设置功能
实现双曲线效果,可以左右滑动、缩放、刷新折线图数据,自定义设置折线颜色
源码及2.1.6jar包:https://mp.csdn.net/console/upDetailed MyChart_Sgf_MPAndroidChart216.zip
一.效果图:
二.快速实现:
implementation files('libs/mpandroidchartlibrary-2-1-6.jar')
在libs中添加上面依赖,注意使用的版本是2.1.6的,和其它版本的使用方法可能有所不同,可以百度一下。
1.主函数代码:
import android.annotation.SuppressLint;
import android.graphics.Color;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import com.github.mikephil.charting.animation.Easing;
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 java.util.ArrayList;
import java.util.List;
/**
* MPAndroidChart实现曲线阴影效果
* https://github.com/stramChen/MPAndroidChart-Bezier-shadow
*
* https://github.com/897532167/ChartManager
*/
public class MainActivity extends AppCompatActivity {
//参考网址 https://github.com/msandroid/androidChartDemo
private LineChart lineChart1, lineChart2;
private LineData lineData;
private LineChart lineChartSgf;
private List<Float> lists = new ArrayList<>();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//设置y轴的数据
lists.clear();
lists.add(666f);
lists.add(122f);
lists.add(245f);
lists.add(678f);
lists.add(555f);
lists.add(521f);
lists.add(111f);
lists.add(190f);
lists.add(280f);
lists.add(366f);
initChart2();
initChart();
Button btRefresh = (Button) findViewById(R.id.bt_refresh);
btRefresh.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// 生成随机测试数
float f = (float) ((Math.random()) * 20 + 50);
lists.add(f);
initChart();
// 像ListView那样的通知数据更新
lineChartSgf.notifyDataSetChanged();
lineChartSgf.invalidate();
}
});
}
@SuppressLint("ResourceType")
private void initChart() {
lineChartSgf = (LineChart) findViewById(R.id.line_chart_sgf);
lineChartSgf.setDescription("单曲线");
//设置x轴的数据
int numX = lists.size();
// //设置折线的名称
// LineChartManager2.setLineName("当月值");
// //设置第二条折线y轴的数据
// LineChartManager2.setLineName1("上月值");
ArrayList<String> xValues = new ArrayList<String>();
for (int i = 0; i < numX; i++) {
// x轴显示的数据,这里默认使用数字下标显示
xValues.add("第" + (i) + "人");
}
// y轴的数据
ArrayList<Entry> yValues = new ArrayList<Entry>();
for (int i = 0; i < numX; i++) {
yValues.add(new Entry(lists.get(i), i));
}
//设置折线的样式
LineDataSet dataSet = new LineDataSet(yValues, "当月值");
// 改变折线样式,用曲线。
// mLineDataSet.setDrawCubic(true);
// 默认是直线
// 曲线的平滑度,值越大越平滑。
// mLineDataSet.setCubicIntensity(0.2f);
// 填充曲线下方的区域,红色,半透明。
dataSet.setDrawFilled(true);
dataSet.setFillAlpha(50);
dataSet.setFillColor(Color.RED);
// dataSet.setFillColor(R.drawable.gradient_chart_bg2);
int[] colors = { getResources().getColor(R.color.colorAccent),
getResources().getColor(android.R.color.white) };
// dataSet.setFillColor(getResources().getColor(R.drawable.gradient_chart_bg2));
//设置曲线下方渐变的阴影
// lineDataSet.setDrawFilled(true);
// lineDataSet.setFillDrawable(getResources().getDrawable(R.drawable.line_gradient_bg_shape));
//用y轴的集合来设置参数
dataSet.setLineWidth(1.75f); // 线宽
dataSet.setCircleSize(2f);// 显示的圆形大小
dataSet.setColor(Color.rgb(89, 194, 230));// 折线显示颜色
dataSet.setCircleColor(Color.rgb(89, 194, 230));// 圆形折点的颜色
dataSet.setHighLightColor(Color.GREEN); // 高亮的线的颜色
dataSet.setHighlightEnabled(true);
dataSet.setValueTextColor(Color.rgb(89, 194, 230)); //数值显示的颜色
dataSet.setValueTextSize(8f); //数值显示的大小
ArrayList<LineDataSet> dataSets = new ArrayList<>();
dataSets.add(dataSet);
//构建一个LineData 将dataSets放入
LineData lineData = new LineData(xValues, dataSets);
lineChartSgf.setData(lineData);
lineChartSgf.setDrawBorders(false); //在折线图上添加边框
//lineChart.setDescription("时间/数据"); //数据描述
lineChartSgf.setDrawGridBackground(false); //表格颜色
lineChartSgf.setGridBackgroundColor(Color.GRAY & 0x70FFFFFF); //表格的颜色,设置一个透明度
lineChartSgf.setTouchEnabled(true); //可点击
lineChartSgf.setDragEnabled(true); //可拖拽
lineChartSgf.setScaleEnabled(false); //可缩放
lineChartSgf.setPinchZoom(false);
lineChartSgf.setBackgroundColor(Color.WHITE); //设置背景颜色
lineChartSgf.setData(lineData);
Legend mLegend = lineChartSgf.getLegend(); //设置标示,就是那个一组y的value的
mLegend.setForm(Legend.LegendForm.SQUARE); //样式
mLegend.setFormSize(6f); //字体
mLegend.setTextColor(Color.GRAY); //颜色
lineChartSgf.setVisibleXRange(0, 4); //x轴可显示的坐标范围
XAxis xAxis = lineChartSgf.getXAxis(); //x轴的标示
xAxis.setPosition(XAxis.XAxisPosition.BOTTOM); //x轴位置
xAxis.setTextColor(Color.GRAY); //字体的颜色
xAxis.setTextSize(10f); //字体大小
xAxis.setGridColor(Color.GRAY);//网格线颜色
xAxis.setDrawGridLines(false); //不显示网格线
YAxis axisLeft = lineChartSgf.getAxisLeft(); //y轴左边标示
YAxis axisRight = lineChartSgf.getAxisRight(); //y轴右边标示
axisLeft.setTextColor(Color.GRAY); //字体颜色
axisLeft.setTextSize(10f); //字体大小
//axisLeft.setAxisMaxValue(800f); //最大值
axisLeft.setLabelCount(5, true); //显示格数
axisLeft.setGridColor(Color.GRAY); //网格线颜色
axisRight.setDrawAxisLine(false);
axisRight.setDrawGridLines(false);
axisRight.setDrawLabels(false);
//设置动画效果
lineChartSgf.animateY(2000, Easing.EasingOption.Linear);
lineChartSgf.animateX(2000, Easing.EasingOption.Linear);
lineChartSgf.invalidate();
}
private void initChart2() {
lineChart2 = (LineChart) findViewById(R.id.line_chart);
//设置图表的描述
lineChart2.setDescription("双曲线");
//设置x轴的数据
int numX = 24;
//设置y轴的数据
float[] datas1 = {536, 123, 769, 432, 102, 26, 94, 85, 536, 123, 769, 432, 102, 26, 94, 85, 536, 123, 769, 432, 102, 26, 94, 85};//数据
float[] datas2 = {736, 123, 369, 132, 82, 126, 94, 85, 136, 123, 369, 632, 102, 126, 94, 85, 136, 123, 269, 432, 102, 26, 494, 85};//数据
//设置折线的名称
LineChartManager2.setLineName("当月值");
//设置第二条折线y轴的数据
LineChartManager2.setLineName1("上月值");
//创建两条折线的图表
lineData = LineChartManager2.initDoubleLineChart(this, lineChart1, numX, datas1, datas2);
LineChartManager2.initDataStyle(lineChart2, lineData, this);
}
}
2.自定义折现图管理者类:LinChartManager2.java
import android.content.Context;
import android.graphics.Color;
import com.github.mikephil.charting.animation.Easing;
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 java.util.ArrayList;
public class LineChartManager2 {
private static String lineName = null;
private static String lineName1 = null;
/**
* 创建一条折线
* @param context 上下文
* @param mLineChart 对象
* @param count X轴的数据
* @param datas Y轴的数据
* @return LineData
*/
public static LineData initSingleLineChart(Context context, LineChart mLineChart, int count, float[] datas) {
ArrayList<String> xValues = new ArrayList<String>();
for (int i = 0; i < count; i++) {
// x轴显示的数据,这里默认使用数字下标显示
xValues.add((i) + ":00");
}
// y轴的数据
ArrayList<Entry> yValues = new ArrayList<Entry>();
for (int i = 0; i < count; i++) {
yValues.add(new Entry(datas[i], i));
}
//设置折线的样式
LineDataSet dataSet = new LineDataSet(yValues, lineName);
//用y轴的集合来设置参数
dataSet.setLineWidth(1.75f); // 线宽
dataSet.setCircleSize(2f);// 显示的圆形大小
dataSet.setColor(Color.rgb(89, 194, 230));// 折线显示颜色
dataSet.setCircleColor(Color.rgb(89, 194, 230));// 圆形折点的颜色
dataSet.setHighLightColor(Color.GREEN); // 高亮的线的颜色
dataSet.setHighlightEnabled(true);
dataSet.setValueTextColor(Color.rgb(89, 194, 230)); //数值显示的颜色
dataSet.setValueTextSize(8f); //数值显示的大小
ArrayList<LineDataSet> dataSets = new ArrayList<>();
dataSets.add(dataSet);
//构建一个LineData 将dataSets放入
LineData lineData = new LineData(xValues, dataSets);
return lineData;
}
/**
* @param context 上下文
* @param mLineChart 折线图控件
* @param count 折线在x轴的值
* @param datas1 折线在y轴的值
* @param datas2 另一条折线在y轴的值
* @Description:创建两条折线
*/
public static LineData initDoubleLineChart(Context context, LineChart mLineChart, int count, float[] datas1, float[] datas2) {
ArrayList<String> xValues = new ArrayList<String>();
for (int i = 0; i < count; i++) {
// x轴显示的数据,这里默认使用数字下标显示
xValues.add((i) + ":00");
}
// y轴的数据
ArrayList<Entry> yValues1 = new ArrayList<Entry>();
for (int i = 0; i < count; i++) {
yValues1.add(new Entry(datas1[i], i));
}
// y轴的数据
ArrayList<Entry> yValues2 = new ArrayList<Entry>();
for (int i = 0; i < count; i++) {
yValues2.add(new Entry(datas2[i], i));
}
LineDataSet dataSet = new LineDataSet(yValues1, lineName);
//dataSet.enableDashedLine(10f, 10f, 0f);//将折线设置为曲线(即设置为虚线)
//用y轴的集合来设置参数
dataSet.setLineWidth(1.75f); // 线宽
dataSet.setCircleSize(2f);// 显示的圆形大小
dataSet.setColor(Color.rgb(89, 194, 230));// 折线显示颜色
dataSet.setCircleColor(Color.rgb(89, 194, 230));// 圆形折点的颜色
dataSet.setHighLightColor(Color.GREEN); // 高亮的线的颜色
dataSet.setHighlightEnabled(true);
dataSet.setValueTextColor(Color.rgb(89, 194, 230)); //数值显示的颜色
dataSet.setValueTextSize(8f); //数值显示的大小
LineDataSet dataSet1 = new LineDataSet(yValues2, lineName1);
//用y轴的集合来设置参数
dataSet1.setLineWidth(1.75f);
dataSet1.setCircleSize(2f);
dataSet1.setColor(Color.rgb(252, 76, 122));
dataSet1.setCircleColor(Color.rgb(252, 76, 122));
dataSet1.setHighLightColor(Color.GREEN);
dataSet1.setHighlightEnabled(true);
dataSet1.setValueTextColor(Color.rgb(252, 76, 122));
dataSet1.setValueTextSize(8f);
//构建一个类型为LineDataSet的ArrayList 用来存放所有 y的LineDataSet 他是构建最终加入LineChart数据集所需要的参数
ArrayList<LineDataSet> dataSets = new ArrayList<>();
//将数据加入dataSets
dataSets.add(dataSet);
dataSets.add(dataSet1);
//构建一个LineData 将dataSets放入
LineData lineData = new LineData(xValues, dataSets);
return lineData;
}
/**
* @Description:初始化图表的样式
*/
public static void initDataStyle(LineChart lineChart, LineData lineData, Context context) {
//设置点击折线点时,显示其数值
// MyMakerView mv = new MyMakerView(context, R.layout.item_mark_layout);
// mLineChart.setMarkerView(mv);
lineChart.setDrawBorders(false); //在折线图上添加边框
//lineChart.setDescription("时间/数据"); //数据描述
lineChart.setDrawGridBackground(false); //表格颜色
lineChart.setGridBackgroundColor(Color.GRAY & 0x70FFFFFF); //表格的颜色,设置一个透明度
lineChart.setTouchEnabled(true); //可点击
lineChart.setDragEnabled(true); //可拖拽
lineChart.setScaleEnabled(true); //可缩放
lineChart.setPinchZoom(false);
lineChart.setBackgroundColor(Color.WHITE); //设置背景颜色
lineChart.setData(lineData);
Legend mLegend = lineChart.getLegend(); //设置标示,就是那个一组y的value的
mLegend.setForm(Legend.LegendForm.SQUARE); //样式
mLegend.setFormSize(6f); //字体
mLegend.setTextColor(Color.GRAY); //颜色
lineChart.setVisibleXRange(0, 4); //x轴可显示的坐标范围
XAxis xAxis = lineChart.getXAxis(); //x轴的标示
xAxis.setPosition(XAxis.XAxisPosition.BOTTOM); //x轴位置
xAxis.setTextColor(Color.GRAY); //字体的颜色
xAxis.setTextSize(10f); //字体大小
xAxis.setGridColor(Color.GRAY);//网格线颜色
xAxis.setDrawGridLines(false); //不显示网格线
YAxis axisLeft = lineChart.getAxisLeft(); //y轴左边标示
YAxis axisRight = lineChart.getAxisRight(); //y轴右边标示
axisLeft.setTextColor(Color.GRAY); //字体颜色
axisLeft.setTextSize(10f); //字体大小
//axisLeft.setAxisMaxValue(800f); //最大值
axisLeft.setLabelCount(5, true); //显示格数
axisLeft.setGridColor(Color.GRAY); //网格线颜色
axisRight.setDrawAxisLine(false);
axisRight.setDrawGridLines(false);
axisRight.setDrawLabels(false);
//设置动画效果
lineChart.animateY(2000, Easing.EasingOption.Linear);
lineChart.animateX(2000, Easing.EasingOption.Linear);
lineChart.invalidate();
//lineChart.animateX(2500); //立即执行动画
}
/**
* @param name
* @Description:设置折线的名称
*/
public static void setLineName(String name) {
lineName = name;
}
/**
* @param name
* @Description:设置另一条折线的名称
*/
public static void setLineName1(String name) {
lineName1 = name;
}
}
3.主函数布局:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<com.github.mikephil.charting.charts.LineChart
android:layout_marginTop="10dp"
android:id="@+id/line_chart"
android:layout_width="match_parent"
android:layout_height="240dp" />
<com.github.mikephil.charting.charts.LineChart
android:layout_marginTop="10dp"
android:id="@+id/line_chart_sgf"
android:layout_width="match_parent"
android:layout_height="240dp" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<Button
android:id="@+id/bt_refresh"
android:text="刷新数据"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
</LinearLayout>
三.其它描述:
1.关于折线图的临界点设置:
//设置限制临界线
LimitLine limitLine = new LimitLine(200f, "临界点");//临界点
limitLine.setLineColor(Color.RED);
limitLine.setLineWidth(1.5f);
limitLine.setTextSize(15f);
limitLine.setTextColor(Color.RED);
// LimitLine avgLine = new LimitLine((float) navg);
// avgLine.enableDashedLine(5.0f, 3.0f, 3.0f);
// avgLine.setLineColor(Color.parseColor("#33CC33"));
lineChartSgf.getAxisLeft().addLimitLine(limitLine);
//设置限制临界线
LimitLine limitLineL = new LimitLine(200f, "临界点");//临界点
limitLineL.setLineColor(Color.RED);
limitLineL.setLineWidth(1.5f);
limitLineL.setTextSize(15f);
limitLineL.setTextColor(Color.RED);
limitLineL.enableDashedLine(5f,3f,0); //设置虚线
lineChartSgf.getAxisLeft().addLimitLine(limitLineL);
//设置均值
LimitLine ll2 = new LimitLine(5, "均值");
ll2.setLabel("均值");
ll2.setTextColor(Color.parseColor("#5dbcfe"));
ll2.setLineWidth(1f);
ll2.setEnabled(true);
ll2.setLineColor(Color.parseColor("#5dbcfe"));
ll2.enableDashedLine(5f, 10f, 0f);//三个参数,第一个线宽长度,第二个线段之间宽度,第三个一般为0,是个补偿
ll2.setLabelPosition(LimitLine.LimitLabelPosition.RIGHT_BOTTOM);//标签位置
ll2.setTextSize(10f);
lineChart.getAxisLeft().addLimitLine(ll2);
2.设置 MPAndroidChart LineChart的曲线阴影效果:
// 填充曲线下方的区域,红色,半透明。
dataSet.setDrawFilled(true);
dataSet.setFillAlpha(50);
dataSet.setFillColor(Color.RED);
// dataSet.setFillColor(R.drawable.gradient_chart_bg2);
int[] colors = { getResources().getColor(R.color.colorAccent),
getResources().getColor(android.R.color.white) };
// dataSet.setFillColor(getResources().getColor(R.drawable.gradient_chart_bg2));
//设置曲线下方渐变的阴影
// lineDataSet.setDrawFilled(true);
// lineDataSet.setFillDrawable(getResources().getDrawable(R.drawable.line_gradient_bg_shape));
目前只可以实现图中的一种颜色,当前版本设置渐变色曲线阴影效果没有效果,MPAndroidChart3.0以上版本应该是支持的,2.1.6版本的jar包不清楚,有知道的话可以说一下。
3.设置动画效果:
// 设置动画
chart.animateX(8000);
chart.animateY(8000);
chart.animateXY(8000, 8000);
chart.animateY(8000, Easing.EasingOption.EaseInElastic );
4.设置图例 Legend:
Legend mLegend = lineChart.getLegend(); //设置标示,就是那个一组y的value的
// mLegend.setForm(Legend.LegendForm.SQUARE); //方形样式
// mLegend.setForm(Legend.LegendForm.CIRCLE); //圆形样式
mLegend.setForm(Legend.LegendForm.LINE); //横线的样式
mLegend.setFormSize(6f); //字体
// mLegend.setXEntrySpace(6f); //设置在水平轴上 legend-entries 的间隙
mLegend.setYEntrySpace(6f); //设置在垂直轴上 legend-entries 的间隙
mLegend.setFormToTextSpace(6f); //设置 legend-form 和 legend-label 之间的空间
mLegend.setWordWrapEnabled(true); //设置 Legend 是否自动换行? 目前仅支持BelowChartLeft,BelowChartRight
mLegend.setTextColor(Color.RED); //设置字体颜色
mLegend.setPosition(Legend.LegendPosition.BELOW_CHART_LEFT); //设置显示下位置在左侧
// mLegend.setPosition(Legend.LegendPosition.BELOW_CHART_RIGHT); //设置显示下位置在右侧
// mLegend.setPosition(Legend.LegendPosition.BELOW_CHART_CENTER); //设置显示下位置在中间
// mLegend.setPosition(Legend.LegendPosition.RIGHT_OF_CHART); //设置显示图平行的右侧
// mLegend.setPosition(Legend.LegendPosition.LEFT_OF_CHART); //设置显示图平行的左侧
// mLegend.setPosition(Legend.LegendPosition.RIGHT_OF_CHART_CENTER); //设置显示图平行的右侧据居中
// mLegend.setPosition(Legend.LegendPosition.LEFT_OF_CHART_INSIDE); //
// mLegend.setPosition(Legend.LegendPosition.PIECHART_CENTER); //PieChart独有,折线图会显示在中间
// mLegend.setPosition(Legend.LegendPosition.LEFT_OF_CHART_CENTER); //设置显示图平行的左侧据居中
mLegend.setTypeface(Typeface.DEFAULT); //设置图例标签的字体
// mLegend.setForm(Legend.LegendForm.NONE);//不绘制图形
// mLegend.setForm(Legend.LegendForm.EMPTY);;//不绘制图形保留空间
//隐藏Lengend
mLegend.setEnabled(true);
//绘制长方形
legend.setForm(Legend.LegendForm.LINE); // 线
legend.setFormSize(14f); // 图形大小
legend.setFormLineWidth(9f); // 图形线宽
legend.setForm(Legend.LegendForm.DEFAULT); //绘制默认图形,默认为圆形
//设置虚线
legend.setForm(Legend.LegendForm.LINE); // 线
legend.setFormSize(32f); // 图形大小
// 设置虚线图形
legend.setFormLineDashEffect(
new DashPathEffect(new float[]{12f,12f,12f}, 10f));
legend.setOrientation(Legend.LegendOrientation.VERTICAL);//默认是水平排列,这里我改为垂直排列
//设置图例的摆放位置
// 水平:居中
legend.setHorizontalAlignment(Legend.LegendHorizontalAlignment.CENTER);
// 垂直:居上
legend.setVerticalAlignment(Legend.LegendVerticalAlignment.TOP);
//设置自定义图形:
List<LegendEntry> entries = new ArrayList<>();
entries.add(new LegendEntry());
entries.add(new LegendEntry(
"A",
Legend.LegendForm.LINE,
14f,
9f,
null,
Color.RED)
);
entries.add(new LegendEntry(
"B",
Legend.LegendForm.CIRCLE,
14f,
0f,
null,
Color.GREEN)
);
entries.add(new LegendEntry(
"C",
Legend.LegendForm.SQUARE,
14f,
0f,
null,
Color.BLUE));
legend.setCustom(entries);
//设置额外图例:
legend.setExtra(new LegendEntry[]{
new LegendEntry(),
new LegendEntry(
"A",
Legend.LegendForm.LINE,
14f,
9f,
null,
Color.RED),
new LegendEntry(
"B",
Legend.LegendForm.CIRCLE,
14f,
0f,
null,
Color.GREEN),
new LegendEntry(
"C",
Legend.LegendForm.SQUARE,
14f,
0f,
null,
Color.BLUE)
});
四.推荐:
https://github.com/PhilJay/MPAndroidChart
https://github.com/zgeekandroid/hellocharts-android
https://github.com/diogobernardino/WilliamChart
极其精美而又强大的 Android 数据可视化图表框架,支持柱状图、条形图、折线图、曲线图、折线填充