Detailed Android Chart Mpandroidchart line chart _android

Source: Internet
Author: User

1. Introduce

Mpandroidchart GitHub Address

The strength of the mpandroidchart is not to say more, the latest version is 3.0.1, in the new version of many methods have been discarded, this should be noted that most of the information found on the Internet is about the old version, today to implement a line chart, the process recorded, share to everyone.

Effect Chart:

2. Introduction of Open Source Library

Add the following code to the Build.gradle file in the project root directory

allprojects {
  repositories {
    maven {URL ' Https://jitpack.io '}
  }
}

Adding dependencies to the Buil.gradle file in the app root directory

dependencies {
  compile ' com.github.philjay:mpandroidchart:v3.0.1 '
}

3. To achieve

In the project, I extracted the graph-related functions into a tool class chartutils.

Initializing a chart

The Initchart method is used to set the function of the chart and the style of the display, in which you annotate the code for scaling and animation, and you do not need to invoke the Invalidate method of the chart if you want to use animation.

/** * Initialization Chart * * @param Chart Original chart * @return Initialized chart */public static Linechart Initchart (Linechart chart) {//not displayed
  Data Description Chart.getdescription (). setenabled (false);
  No data, display "No Data" chart.setnodatatext ("temporarily no data");
  Do not display table color Chart.setdrawgridbackground (FALSE);
  Chart.setscaleenabled (false) cannot be scaled;
  Do not display the value chart.getaxisright (). SetEnabled (False) to the right of the y-axis;
  Do not show legend Legend Legend = Chart.getlegend ();
  Legend.setenabled (FALSE);

  Offset 15DP to the left, offset the y-axis 30dp chart.setextraleftoffset (-15) offset to the right;
  Xaxis Xaxis = Chart.getxaxis ();
  Do not show x-axis xaxis.setdrawaxisline (false);
  Set the position of the x-axis data xaxis.setposition (XAxis.XAxisPosition.BOTTOM);
  Xaxis.settextcolor (Color.White);
  Xaxis.settextsize (12);
  Xaxis.setgridcolor (Color.parsecolor ("#30FFFFFF"));

  Sets the x-axis data offset Xaxis.setyoffset (-12);
  YAxis YAxis = Chart.getaxisleft ();
  Do not show y-axis yaxis.setdrawaxisline (false);
  Sets the position of the y-axis data yaxis.setposition (YAxis.YAxisLabelPosition.OUTSIDE_CHART); Do not emit horizontal straight yaxis.setdrawgridl from the Y axisInes (FALSE);
  Yaxis.settextcolor (Color.White);
  Yaxis.settextsize (12);
  Sets the y-axis data offset yaxis.setxoffset (30);
  Yaxis.setyoffset (-3);

  Yaxis.setaxisminimum (0);
  Matrix matrix = new Matrix ();
  X-axis Scaling 1.5 times times//matrix.postscale (1.5f, 1f);
  Zoom//chart.getviewporthandler () before the chart animation is displayed (). Refresh (Matrix, chart, false);
  X-axis Animation//chart.animatex (2000);
  Chart.invalidate ();
return chart;

 }

Set chart data

The Setchartdata method is used to set the data displayed by the chart and the properties of the polyline.

/** *
 Set Chart Data * *
 @param Chart Chart
 * @param values Data
/public static void Setchartdata (Linechart Chart, list<entry> values) {
  linedataset linedataset;

  if (chart.getdata ()!= null && chart.getdata (). Getdatasetcount () > 0) {
    Linedataset = (linedataset) chart. GetData (). Getdatasetbyindex (0);
    Linedataset.setvalues (values);
    Chart.getdata (). notifydatachanged ();
    Chart.notifydatasetchanged ();
  } else {
    Linedataset = new Linedataset (values, "");
    Sets the curve color
    linedataset.setcolor (Color.parsecolor ("#FFFFFF"));
    Set Smooth curve
    Linedataset.setmode (LineDataSet.Mode.CUBIC_BEZIER);
    Small dot
    linedataset.setdrawcircles (false) without display of coordinate points;
    Data
    Linedataset.setdrawvalues (false) with no coordinate point displayed;
    Do not display the locator line
    linedataset.sethighlightenabled (false);

    Linedata data = new Linedata (linedataset);
    Chart.setdata (data);
    Chart.invalidate ();
  }


Update chart

The Notifydatasetchanged method is used to update the chart and dynamically display the X axis label.

/** *
 Update chart * *
 @param Chart   Chart
 * @param values  data
 * @param valuetype data type
* * public static void Notifydatasetchanged (Linechart chart, list<entry> values,
                    final int valuetype) {
  Chart.getxaxis (). Setvalueformatter (New Iaxisvalueformatter () {
    @Override public
    String GetFormattedValue (float value, axisbase axis) {return
      xvaluesprocess (valuetype) [(int) value];
    }
  });

  Chart.invalidate ();
  Setchartdata (chart, values);
}

X-Axis data processing

The Xvaluesprocess method is used to process x-axis data.

The x axis can display three types of data, namely today's data, this week's data, and this month's data.

/** * x-axis data processing * @param valuetype data type * @return X-axis data/private static string[] xvaluesprocess (int valuetype) {S

  Tring[] Week = {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"};
    if (valuetype = = Dayvalue) {//today string[] dayvalues = new STRING[7];
    Long currenttime = System.currenttimemillis ();
      for (int i = 6; I >= 0; i--) {Dayvalues[i] = timeutils.datetostring (currenttime, timeutils.dateformat_day);
    CurrentTime-= (3 * 60 * 60 * 1000);

  return dayvalues;
    else if (valuetype = = Weekvalue) {//this week string[] weekvalues = new STRING[7];
    Calendar calendar = Calendar.getinstance ();

    int currentweek = Calendar.get (Calendar.day_of_week);
      for (int i = 6; I >= 0; i--) {weekvalues[i] = week[currentweek-1];
      if (Currentweek = = 1) {Currentweek = 7;
      else {currentweek = 1;

  } return weekvalues; else if (valuetype = Monthvalue) {//this month string[] monthvalues = new String[7];
    Long currenttime = System.currenttimemillis ();
      for (int i = 6; I >= 0; i--) {Monthvalues[i] = timeutils.datetostring (currenttime, timeutils.dateformat_month);
    CurrentTime-= (4 * 24 * 60 * 60 * 1000);
  return monthvalues;
Return to New string[]{};

 }

Use in activity

Chartutils.initchart (chart);
Chartutils.notifydatasetchanged (chart, GetData (), chartutils.dayvalue);

Layout file

<com.github.mikephil.charting.charts.linechart
    android:id= "@+id/chart"
    android:layout_width= "Match_ Parent "
    android:layout_height=" Match_parent "/>

4. The problems encountered

    • The Xaxis.setxoffset () method does not work when you set the x-axis horizontal translation, which allowed me to study for a long time, and finally, using the chart translation Method Chart.setextraleftoffset () to offset the translation of the y-axis, has been submitted to the issues, There are answers that will be updated in the blog.
    • At present, y-axis data can only be displayed by setting the maximum, the minimum value, display the number of ways to display the data (if not set will automatically calculate), has not found a custom display data methods, there are understanding of the small partner can leave a message to tell me AH.
    • Custom x axis Data remember to calculate the corresponding value, the demo only used 7 points, so relatively simple, but more than x axis data, it is necessary to calculate, if there is no understanding of the place can give me a message or send DMS.

5. Written in the final

In the process of implementation, Mpandroidchart issues helped a lot of busy, there are many people and I encountered the same problem, the original did not check the habit of issues, and get a new skill.

Official documents

Full demo Download

The above is the entire content of this article, I hope to help you learn, but also hope that we support the cloud habitat community.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.