300字范文,内容丰富有趣,生活中的好帮手!
300字范文 > android 大屏图表 MPAndroidChart 折线图 曲线图 柱状图 圆角柱状图 条形图

android 大屏图表 MPAndroidChart 折线图 曲线图 柱状图 圆角柱状图 条形图

时间:2023-10-08 04:03:53

相关推荐

android 大屏图表 MPAndroidChart 折线图 曲线图 柱状图 圆角柱状图 条形图

//图表库implementation 'com.github.PhilJay:MPAndroidChart:v3.1.0'

X轴:XAxis

Y轴:YAxis

图例:Legend

描述:Description

限制线:LimitLine

显示的视图:MarkerView (就是选择中的时候显示的样子)

折线图:

layout

<?xml version="1.0" encoding="utf-8"?><RelativeLayout xmlns:android="/apk/res/android"android:layout_width="match_parent"android:layout_height="match_parent"android:background="@color/black"android:orientation="vertical"><com.github.mikephil.charting.charts.LineChartandroid:id="@+id/chart1"android:layout_width="match_parent"android:layout_height="match_parent"/></RelativeLayout>

private LineChart charts ;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,WindowManager.LayoutParams.FLAG_FULLSCREEN);setContentView(R.layout.activity_colored_lines);charts = findViewById(R.id.chart1); MpAndroidchart(charts);}private void MpAndroidchart(LineChart charts) {//是否显示边框charts.setDrawBorders(false);//得到X轴XAxis xAxis = charts.getXAxis();//设置X轴的位置 (不设置默认在上方)xAxis.setPosition(XAxis.XAxisPosition.BOTTOM);//设置X轴坐标之间的最小间隔(因为此图有缩放功能,X轴,Y轴可设置可缩放)xAxis.setGranularity(1f);//设置X轴的刻度数量 第二个参数表示是否平均分配xAxis.setLabelCount(7, true);//设置X轴的值(最小值、最大值、然后会根据设置的刻度数量自动分配刻度显示)xAxis.setAxisMinimum(1f);xAxis.setAxisMaximum(7f);//X轴文字颜色xAxis.setTextColor(Color.WHITE);//X轴网格线颜色xAxis.setGridColor(Color.TRANSPARENT);//X轴颜色xAxis.setAxisLineColor(Color.WHITE);//设置X轴文字显示xAxis.setValueFormatter(new IAxisValueFormatter() {@Overridepublic String getFormattedValue(float value, AxisBase axis) {return (int)value+"月";}})//设置X轴动画// charts.animateX(3000);//得到Y轴YAxis leftYAxis = charts.getAxisLeft();YAxis rightYAxis =charts.getAxisRight();//设置从左侧Y轴值leftYAxis.setAxisMinimum(0f);leftYAxis.setAxisMaximum(100f);//设置从左侧Y轴值// rightYAxis.setAxisMinimum(0f);// rightYAxis.setAxisMaximum(100f);//右侧Y轴不显示rightYAxis.setEnabled(false);//设置Y轴坐标之间的最小间隔(因为此图有缩放功能,X轴,Y轴可设置可缩放)leftYAxis.setGranularity(1f);//设置Y轴的刻度数量 第二个参数表示是否平均分配leftYAxis.setLabelCount(10, true);//Y轴文字颜色leftYAxis.setTextColor(Color.WHITE);//Y轴网格线颜色leftYAxis.setGridColor(Color.argb(100,255,255,255));//Y轴颜色leftYAxis.setAxisLineColor(Color.WHITE);//设置X轴动画// charts.animateY(3000);// //得到限制线// LimitLine limitLine = new LimitLine(95,"高限制性");// //宽度// limitLine.setLineWidth(4f);// //字体大小// limitLine.setTextSize(10f);// //字体颜色// limitLine.setTextColor(Color.RED);// //线大小// limitLine.setLineColor(Color.BLUE);// //Y轴添加限制线// leftYAxis.addLimitLine(limitLine);// //X轴添加限制线// xAxis.addLimitLine(limitLine);//得到Legend (下边的颜色线)Legend legend = charts.getLegend();//设置Legend 文本颜色legend.setTextColor(Color.WHITE);//设置Legend 在顶部显示legend.setVerticalAlignment(Legend.LegendVerticalAlignment.TOP);//设置Legend 在右侧显示legend.setHorizontalAlignment(Legend.LegendHorizontalAlignment.RIGHT);//设置Legend 在横向显示legend.setOrientation(Legend.LegendOrientation.HORIZONTAL);//设置标签是否换行(当多条标签时 需要换行显示)//true:可换行。false:不换行legend.setWordWrapEnabled(false);//是否显示Lengend//true:显示。false:不显示legend.setEnabled(true);//得到描述Description description = new Description();//是否显示描述//true:显示。false:不显示description.setEnabled(true);//设置x轴描述description.setText("单位:命中次数");description.setTextColor(Color.WHITE);charts.setDescription(description);//设置XY轴动画charts.animateXY(3000, 3000);//设置数据List<Entry> entries = new ArrayList<>();for (int i = 0; i < 24; i++) {entries.add(new Entry(i, (float) (Math.random()) * 80));}//一个LineDataSet就是一条线LineDataSet lineDataSet = new LineDataSet(entries, "温度");//设置value的字体颜色lineDataSet.setValueTextColor(Color.WHITE);//设置曲线值的圆点是实心还是空心lineDataSet.setDrawCircleHole(false);//设置显示值的字体大小lineDataSet.setValueTextSize(9f);//线模式为圆滑曲线(默认折线)// lineDataSet.setMode(LineDataSet.Mode.HORIZONTAL_BEZIER);//设置折线颜色lineDataSet.setColor(Color.WHITE);//设置小圆点颜色lineDataSet.setCircleColor(Color.WHITE);//设置填充颜色lineDataSet.setDrawFilled(true);lineDataSet.setFillColor(R.color.xian);// 设置拖拽、缩放等charts.setDragEnabled(false);charts.setScaleEnabled(false);charts.setScaleXEnabled(false);charts.setScaleYEnabled(false);// 设置双指缩放charts.setPinchZoom(true);LineData data = new LineData(lineDataSet);charts.setData(data);}

如果想在上方注释这个。

//设置X轴的位置 (不设置默认在上方)// xAxis.setPosition(XAxis.XAxisPosition.BOTTOM);

如果想要XY轴都有线 设置这两个方法。

//X轴网格线颜色xAxis.setGridColor(Color.TRANSPARENT);//Y轴网格线颜色leftYAxis.setGridColor(Color.argb(100,255,255,255));

线模式为圆滑曲线

//线模式为圆滑曲线(默认折线)lineDataSet.setMode(LineDataSet.Mode.HORIZONTAL_BEZIER);

如果不想要填充颜色 :

//设置填充颜色lineDataSet.setDrawFilled(true);lineDataSet.setFillColor(R.color.xian);

设置XY轴 加个单位。

//设置X轴文字显示xAxis.setValueFormatter(new IAxisValueFormatter() {@Overridepublic String getFormattedValue(float value, AxisBase axis) {return (int)value+"月";}});

圆角柱状图

圆角柱状图需修改源码:BarChartRenderer.java drawDataSet方法

if (isCustomFill) {dataSet.getFill(pos).fillRect(c, mRenderPaint,buffer.buffer[j],buffer.buffer[j + 1],buffer.buffer[j + 2],buffer.buffer[j + 3],isInverted ? Fill.Direction.DOWN : Fill.Direction.UP);}else {//这里注释,使用下面的 圆角。//c.drawRect(buffer.buffer[j], buffer.buffer[j + 1], buffer.buffer[j + 2],// buffer.buffer[j + 3], mRenderPaint);RectF rectF=new RectF(buffer.buffer[j], buffer.buffer[j + 1], buffer.buffer[j + 2],buffer.buffer[j + 3]);c.drawRoundRect(rectF,(float)50,(float)50,mRenderPaint);}

<?xml version="1.0" encoding="utf-8"?><RelativeLayout xmlns:android="/apk/res/android"android:layout_width="match_parent"android:background="@color/black"android:layout_height="match_parent"><com.github.mikephil.charting.charts.BarChartandroid:id="@+id/chart1"android:layout_width="match_parent"android:layout_height="match_parent"/> </RelativeLayout>

package com.xxmassdeveloper.mpchartexample;import com.github.ponents.AxisBase;import com.github.ponents.Description;import com.github.mikephil.charting.formatter.IValueFormatter;import com.github.mikephil.charting.renderer.scatter.CircleShapeRenderer;import com.github.mikephil.charting.utils.Fill;import com.github.mikephil.charting.utils.ViewPortHandler;import com.sbas.xueliapplication.R;import android.Manifest;import android.content.Intent;import android.content.pm.PackageManager;import android.graphics.Color;import android.graphics.RectF;import .Uri;import android.os.Bundle;import androidx.core.content.ContextCompat;import android.util.Log;import android.view.Menu;import android.view.MenuItem;import android.view.WindowManager;import android.widget.SeekBar;import android.widget.SeekBar.OnSeekBarChangeListener;import android.widget.TextView;import com.github.mikephil.charting.charts.BarChart;import com.github.ponents.Legend;import com.github.ponents.Legend.LegendForm;import com.github.ponents.XAxis;import com.github.ponents.XAxis.XAxisPosition;import com.github.ponents.YAxis;import com.github.ponents.YAxis.AxisDependency;import com.github.ponents.YAxis.YAxisLabelPosition;import com.github.mikephil.charting.data.BarData;import com.github.mikephil.charting.data.BarDataSet;import com.github.mikephil.charting.data.BarEntry;import com.github.mikephil.charting.data.Entry;import com.github.mikephil.charting.formatter.IAxisValueFormatter;import com.github.mikephil.charting.highlight.Highlight;import com.github.mikephil.charting.interfaces.datasets.IBarDataSet;import com.github.mikephil.charting.interfaces.datasets.IDataSet;import com.github.mikephil.charting.listener.OnChartValueSelectedListener;import com.github.mikephil.charting.utils.MPPointF;import com.xxmassdeveloper.mpchartexample.custom.DayAxisValueFormatter;import com.xxmassdeveloper.mpchartexample.custom.MyAxisValueFormatter;import com.xxmassdeveloper.mpchartexample.custom.XYMarkerView;import com.xxmassdeveloper.mpchartexample.notimportant.DemoBase;import java.util.ArrayList;import java.util.List;import static com.github.ponents.Legend.LegendForm.CIRCLE;public class BarChartActivity extends DemoBase implements OnSeekBarChangeListener,OnChartValueSelectedListener {private BarChart chart;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,WindowManager.LayoutParams.FLAG_FULLSCREEN);setContentView(R.layout.activity_barchart);setTitle("BarChartActivity");chart = findViewById(R.id.chart1);BarChart(chart);}ArrayList<BarEntry> barEntries = new ArrayList<>();public void BarChart(BarChart barChart){for (int i = 0; i < 7; i++) {int val = (int) (Math.random() * (30 + 1));barEntries.add(new BarEntry(i+1, val));}//是否显示边框barChart.setDrawBorders(false);//得到X轴XAxis xAxis = barChart.getXAxis();//设置X轴的位置 (不设置默认在上方)xAxis.setPosition(XAxis.XAxisPosition.BOTTOM);//设置X轴坐标之间的最小间隔(因为此图有缩放功能,X轴,Y轴可设置可缩放)xAxis.setGranularity(1);//设置X轴的刻度数量 第二个参数表示是否平均分配xAxis.setLabelCount(12, false);//设置X轴的值(最小值、最大值、然后会根据设置的刻度数量自动分配刻度显示)xAxis.setAxisMinimum(0);xAxis.setAxisMaximum(12);//设置X轴文字显示xAxis.setValueFormatter(new IAxisValueFormatter() {@Overridepublic String getFormattedValue(float value, AxisBase axis) {return (int)value+"月";}});//X轴文字颜色xAxis.setTextColor(Color.WHITE);//X轴网格线颜色xAxis.setGridColor(Color.TRANSPARENT);//X轴颜色xAxis.setAxisLineColor(Color.WHITE);//设置X轴动画// mBinding.lineChart.animateX(3000);//得到Y轴YAxis leftYAxis = barChart.getAxisLeft();YAxis rightYAxis = barChart.getAxisRight();//设置从左侧Y轴值leftYAxis.setAxisMinimum(0);leftYAxis.setAxisMaximum(31);//设置从左侧Y轴值// rightYAxis.setAxisMinimum(0f);// rightYAxis.setAxisMaximum(100f);//右侧Y轴不显示rightYAxis.setEnabled(false);//设置Y轴坐标之间的最小间隔(因为此图有缩放功能,X轴,Y轴可设置可缩放)leftYAxis.setGranularity(1);//设置Y轴的刻度数量 第二个参数表示是否平均分配leftYAxis.setLabelCount(6, true);//Y轴文字颜色leftYAxis.setTextColor(Color.WHITE);//Y轴网格线颜色leftYAxis.setGridColor(Color.argb(100,14,106,136));//Y轴颜色leftYAxis.setAxisLineColor(Color.WHITE);//设置X轴动画// mBinding.lineChart.animateY(3000);// //得到限制线// LimitLine limitLine = new LimitLine(95,"高限制性");// //宽度// limitLine.setLineWidth(4f);// //字体大小// limitLine.setTextSize(10f);// //字体颜色// limitLine.setTextColor(Color.RED);// //线大小// limitLine.setLineColor(Color.BLUE);// //Y轴添加限制线// leftYAxis.addLimitLine(limitLine);// //X轴添加限制线// xAxis.addLimitLine(limitLine);//得到Legend (下边的颜色线)Legend legend = barChart.getLegend();//设置Legend 文本颜色legend.setTextColor(Color.WHITE);//设置Legend 在顶部显示legend.setVerticalAlignment(Legend.LegendVerticalAlignment.TOP);//设置Legend 在右侧显示legend.setHorizontalAlignment(Legend.LegendHorizontalAlignment.RIGHT);//设置Legend 在横向显示legend.setOrientation(Legend.LegendOrientation.HORIZONTAL);//设置标签是否换行(当多条标签时 需要换行显示)//true:可换行。false:不换行legend.setWordWrapEnabled(false);//是否显示Lengend//true:显示。false:不显示legend.setEnabled(true);//得到描述Description description = new Description();//是否显示描述//true:显示。false:不显示description.setEnabled(true);//设置x轴描述description.setText("单位:天数");description.setTextColor(Color.WHITE);barChart.setDescription(description);//设置XY轴动画barChart.animateXY(3000, 3000);//一个LineDataSet就是一条线BarDataSet barDataSet = new BarDataSet(barEntries, "");//设置value的字体颜色barDataSet.setValueTextColor(Color.argb(100,14,106,136));barDataSet.setValueFormatter(new IValueFormatter() {@Overridepublic String getFormattedValue(float value, Entry entry, int dataSetIndex, ViewPortHandler viewPortHandler) {return (int)value+"";}});List<Fill> gradientFills = new ArrayList<>();int startColor1 = ContextCompat.getColor(this, android.R.color.holo_orange_light);int endColor1 = ContextCompat.getColor(this, android.R.color.holo_blue_dark);gradientFills.add(new Fill(startColor1, endColor1));// barDataSet.setFills(gradientFills);//设置曲线值的圆点是实心还是空心// barDataSet.setDrawCircleHole(false);//设置显示值的字体大小barDataSet.setValueTextSize(10f);//设置折线颜色barDataSet.setColor(Color.argb(100,14,106,136));// 设置拖拽、缩放等barChart.setDragEnabled(false);barChart.setScaleEnabled(false);barChart.setScaleXEnabled(false);barChart.setScaleYEnabled(false);// 设置双指缩放barChart.setPinchZoom(false);BarData data = new BarData(barDataSet);barChart.setData(data);}@Overridepublic boolean onCreateOptionsMenu(Menu menu) {getMenuInflater().inflate(R.menu.bar, menu);return true;}@Overridepublic boolean onOptionsItemSelected(MenuItem item) {switch (item.getItemId()) {case R.id.viewGithub: {Intent i = new Intent(Intent.ACTION_VIEW);i.setData(Uri.parse("/PhilJay/MPAndroidChart/blob/master/MPChartExample/src/com/xxmassdeveloper/mpchartexample/BarChartActivity.java"));startActivity(i);break;}case R.id.actionToggleValues: {for (IDataSet set : chart.getData().getDataSets())set.setDrawValues(!set.isDrawValuesEnabled());chart.invalidate();break;}case R.id.actionToggleIcons: {for (IDataSet set : chart.getData().getDataSets())set.setDrawIcons(!set.isDrawIconsEnabled());chart.invalidate();break;}case R.id.actionToggleHighlight: {if (chart.getData() != null) {chart.getData().setHighlightEnabled(!chart.getData().isHighlightEnabled());chart.invalidate();}break;}case R.id.actionTogglePinch: {if (chart.isPinchZoomEnabled())chart.setPinchZoom(false);elsechart.setPinchZoom(true);chart.invalidate();break;}case R.id.actionToggleAutoScaleMinMax: {chart.setAutoScaleMinMaxEnabled(!chart.isAutoScaleMinMaxEnabled());chart.notifyDataSetChanged();break;}case R.id.actionToggleBarBorders: {for (IBarDataSet set : chart.getData().getDataSets())((BarDataSet) set).setBarBorderWidth(set.getBarBorderWidth() == 1.f ? 0.f : 1.f);chart.invalidate();break;}case R.id.animateX: {chart.animateX(2000);break;}case R.id.animateY: {chart.animateY(2000);break;}case R.id.animateXY: {chart.animateXY(2000, 2000);break;}case R.id.actionSave: {if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {saveToGallery();} else {requestStoragePermission(chart);}break;}}return true;}@Overridepublic void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {chart.invalidate();}@Overrideprotected void saveToGallery() {saveToGallery(chart, "BarChartActivity");}@Overridepublic void onStartTrackingTouch(SeekBar seekBar) {}@Overridepublic void onStopTrackingTouch(SeekBar seekBar) {}private final RectF onValueSelectedRectF = new RectF();@Overridepublic void onValueSelected(Entry e, Highlight h) {if (e == null)return;RectF bounds = onValueSelectedRectF;chart.getBarBounds((BarEntry) e, bounds);MPPointF position = chart.getPosition(e, AxisDependency.LEFT);Log.i("bounds", bounds.toString());Log.i("position", position.toString());Log.i("x-index","low: " + chart.getLowestVisibleX() + ", high: "+ chart.getHighestVisibleX());MPPointF.recycleInstance(position);}@Overridepublic void onNothingSelected() {}}

package com.xxmassdeveloper.mpchartexample.notimportant;import android.Manifest;import android.content.pm.PackageManager;import android.graphics.Typeface;import android.os.Bundle;import androidx.annotation.NonNull;import androidx.annotation.Nullable;import com.google.android.material.snackbar.Snackbar;import androidx.appcompat.app.AppCompatActivity;import androidx.core.app.ActivityCompat;import android.view.View;import android.widget.Toast;import com.github.mikephil.charting.charts.Chart;import com.sbas.xueliapplication.R;/*** Base class of all Activities of the Demo Application.** @author Philipp Jahoda*/public abstract class DemoBase extends AppCompatActivity implements ActivityCompat.OnRequestPermissionsResultCallback {protected final String[] months = new String[] {"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Okt", "Nov", "Dec"};protected final String[] parties = new String[] {"Party A", "Party B", "Party C", "Party D", "Party E", "Party F", "Party G", "Party H","Party I", "Party J", "Party K", "Party L", "Party M", "Party N", "Party O", "Party P","Party Q", "Party R", "Party S", "Party T", "Party U", "Party V", "Party W", "Party X","Party Y", "Party Z"};private static final int PERMISSION_STORAGE = 0;protected Typeface tfRegular;protected Typeface tfLight;@Overrideprotected void onCreate(@Nullable Bundle savedInstanceState) {super.onCreate(savedInstanceState);tfRegular = Typeface.createFromAsset(getAssets(), "OpenSans-Regular.ttf");tfLight = Typeface.createFromAsset(getAssets(), "OpenSans-Light.ttf");}protected float getRandom(float range, float start) {return (float) (Math.random() * range) + start;}@Overridepublic void onBackPressed() {super.onBackPressed();overridePendingTransition(R.anim.move_left_in_activity, R.anim.move_right_out_activity);}@Overridepublic void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {if (requestCode == PERMISSION_STORAGE) {if (grantResults.length == 1 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {saveToGallery();} else {Toast.makeText(getApplicationContext(), "Saving FAILED!", Toast.LENGTH_SHORT).show();}}}protected void requestStoragePermission(View view) {if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)) {Snackbar.make(view, "Write permission is required to save image to gallery", Snackbar.LENGTH_INDEFINITE).setAction(android.R.string.ok, new View.OnClickListener() {@Overridepublic void onClick(View v) {ActivityCompat.requestPermissions(DemoBase.this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, PERMISSION_STORAGE);}}).show();} else {Toast.makeText(getApplicationContext(), "Permission Required!", Toast.LENGTH_SHORT).show();ActivityCompat.requestPermissions(DemoBase.this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, PERMISSION_STORAGE);}}protected void saveToGallery(Chart chart, String name) {if (chart.saveToGallery(name + "_" + System.currentTimeMillis(), 70))Toast.makeText(getApplicationContext(), "Saving SUCCESSFUL!",Toast.LENGTH_SHORT).show();elseToast.makeText(getApplicationContext(), "Saving FAILED!", Toast.LENGTH_SHORT).show();}protected abstract void saveToGallery();}

柱状图:

源码不动:

if (isCustomFill) {dataSet.getFill(pos).fillRect(c, mRenderPaint,buffer.buffer[j],buffer.buffer[j + 1],buffer.buffer[j + 2],buffer.buffer[j + 3],isInverted ? Fill.Direction.DOWN : Fill.Direction.UP);}else {//这里注释,使用下面的 圆角。c.drawRect(buffer.buffer[j], buffer.buffer[j + 1], buffer.buffer[j + 2],buffer.buffer[j + 3], mRenderPaint);//RectF rectF=new RectF(buffer.buffer[j], buffer.buffer[j + 1], buffer.buffer[j + 2],buffer.buffer[j + 3]);//c.drawRoundRect(rectF,(float)50,(float)50,mRenderPaint);}

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。