Android Open Source Chart library Mpandroidchart document translation (top)

Source: Internet
Author: User
Tags float max



Mpandroidchart is an open source chart library on the Android system. Line and pie charts are currently available, with support for selection, zooming, and drag-and-drop.



Android Open Source Chart Library Mpandroidchar's Githu address:



Https://github.com/PhilJay/MPAndroidChart


Document Address: Https://github.com/PhilJay/MPAndroidChart/wikiAPI Address: https://jitpack.io/com/github/PhilJay/MPAndroidChart/v2.2.5/javadoc/first, Getting Started1. Createdefine Linechart, Barchart, Scatterchart, Candlestickchart, Piechart, Bubblechart or Radarchart in the XML file,


 <com.github.mikephil.charting.charts.LineChart
        android:id="@+id/chart"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

Referencing in activity or fragment


 // in this example, a LineChart is initialized from xml
    LineChart chart = (LineChart) findViewById(R.id.chart);
or create directly


// programmatically create a LineChart
    LineChart chart = new LineChart(Context);

    // get a layout defined in xml
    RelativeLayout rl = (RelativeLayout) findViewById(R.id.relativeLayout);
    rl.add(chart); // add the programmatically created chart
2. Refreshinvalidate (): This method allows the chart to be redrawn. This method is necessary for the chart change to take effect.
Notifydatasetchanged (): Let the chart know that its underlying data has changed and perform all necessary recalculation (offsets, legend, Maxima, minima, ...). This must be called when data is added dynamically.
3. Print Logsetlogenabled (Boolean enabled): Set to true activates the log output. Using this log can have a performance impact, and it's not necessary to turn it off.
4. Chart Stylesome style-related methods that you can use directlyFor more detailed individual chart types and settings, see the wiki page for specific chart settings specific chart settings
SetBackgroundColor (int color): Sets the background of the entire chart view
SetDescription (String desc): Description of the chart in the lower right corner
Setdescriptioncolor (int color): Describes the color of information
Setdescriptionposition (float x, float y): Customizes the description information location.
Setdescriptiontypeface (Typeface t): Custom description Information Font
Setdescriptiontextsize (float size): Custom description information font size, minimum value 6f, maximum 16f.
Setnodatatextdescription (String desc): Sets the description information for empty tables
Setdrawgridbackground (Boolean enabled): Whether to draw a grid background
Setgridbackgroundcolor (int color): Set the grid background color
Setdrawborders (Boolean enabled): whether to draw edges
setBorderColor (int color): Edge color
Setborderwidth (float width): Edge width, Unit DP
Setmaxvisiblevaluecount (int count): Sets the maximum number of visible labels that the chart draws. Effective only when setdrawvalues () is enabled

Second, the interaction of the chartThis library allows you to customize the callback method for the interaction of the gesture with the chart view.
1. Enable/disable interactionSettouchenabled (Boolean enabled): Enable Chart Touch events
Setdragenabled (Boolean enabled): Enable chart Drag events
Setscaleenabled (Boolean enabled): Enable chart Zoom events
Setscalexenabled (Boolean enabled): Enables scaling on the x-axis
Setscaleyenabled (Boolean enabled): Enable scaling on the y-axis
Setpinchzoom (Boolean enabled): XY simultaneous scaling
Setdoubletaptozoomenabled (Boolean enabled): Enable double-click Scaling
Sethighlightperdragenabled (Boolean enabled): Highlight when dragging over the icon drawing canvas
Sethighlightpertapenabled (Boolean enabled): Double-click Highlighting2, the chart reducersetdragdecelerationenabled (Boolean enabled): Continue scrolling after lifting
Setdragdecelerationfrictioncoef (float coef): deceleration interpolation, value range [0,1]. 0 indicates that the stand is stopped. the higher the value, the slower the descent.3, highlight the wayhighlightvalues (highlight[] highs): High-Highlight collection, if empty, all not highlighted
Highlightvalue (int xindex, int datasetindex): The data collection on the x-axis is highlighted. If is-1, all is not high two
GetHighlighted (): Get a collection of high highlights
highlighting using Onchartvalueselectedlistener does not generate a callback. Highlighting can be enabled and disabled through ChartData or DataSet objects. 4. Custom Highlight Symbolsall user input is handled internally by the default Charthighlighter class. It can replace the default Highligher with the following method of customizing the implementation:
Sethighlighter (Charthighlighter highlighter): Implements a custom highlight symbol by inheriting the Charthighlighter class. Use Sethighlighter to set the highlighted symbols for clicks and other actions
5. Select CallbackThe library provides some post-callbacks after the interaction. One of these is the Onchartvalueselectedlistener listener, which is recalled by touching the highlighted value:


public interface OnChartValueSelectedListener {
    /**
    * Called when a value has been selected inside the chart.
    *
    * @param e The selected Entry.
    * @param dataSetIndex The index in the datasets array of the data object
    * the Entrys DataSet is in.
    * @param h the corresponding highlight object that contains information
    * about the highlighted position
    */
    public void onValueSelected(Entry e, int dataSetIndex, Highlight h);
    /**
    * Called when nothing has been selected or an "un-select" has been made.
    */
    public void onNothingSelected();
}
Let your class implement the interface that needs to receive the callback, set it as a listener to the chart

Chart.setonchartvalueselectedlistener (this);
6. Gesture CallbackOnchartgesturelistener This callback can customize gesture manipulation related callbacks

public interface OnChartGestureListener {

    /**
     * Callbacks when a touch-gesture has started on the chart (ACTION_DOWN)
     *
     * @param me
     * @param lastPerformedGesture
     */
    void onChartGestureStart(MotionEvent me, ChartTouchListener.ChartGesture lastPerformedGesture);

    /**
     * Callbacks when a touch-gesture has ended on the chart (ACTION_UP, ACTION_CANCEL)
     *
     * @param me
     * @param lastPerformedGesture
     */
    void onChartGestureEnd(MotionEvent me, ChartTouchListener.ChartGesture lastPerformedGesture);

    /**
     * Callbacks when the chart is longpressed.
     * 
     * @param me
     */
    public void onChartLongPressed(MotionEvent me);

    /**
     * Callbacks when the chart is double-tapped.
     * 
     * @param me
     */
    public void onChartDoubleTapped(MotionEvent me);

    /**
     * Callbacks when the chart is single-tapped.
     * 
     * @param me
     */
    public void onChartSingleTapped(MotionEvent me);

    /**
     * Callbacks then a fling gesture is made on the chart.
     * 
     * @param me1
     * @param me2
     * @param velocityX
     * @param velocityY
     */
    public void onChartFling(MotionEvent me1, MotionEvent me2, float velocityX, float velocityY);

   /**
     * Callbacks when the chart is scaled / zoomed via pinch zoom gesture.
     * 
     * @param me
     * @param scaleX scalefactor on the x-axis
     * @param scaleY scalefactor on the y-axis
     */
    public void onChartScale(MotionEvent me, float scaleX, float scaleY);

   /**
    * Callbacks when the chart is moved / translated via drag gesture.
    *
    * @param me
    * @param dX translation distance on the x-axis
    * @param dY translation distance on the y-axis
    */
    public void onChartTranslate(MotionEvent me, float dX, float dY);
}
Third, Axis axisbase It is mainly the Axisbase class, which is the base class for Xaxis and YAxis.
The methods mentioned below can be applied to both axes.
The Axis class allows custom styles and (can be included) by the following components/parts:
Label (aligned in Vertical (Y-axis) or horizontal (x-axis), which contains axis description values
Draw a so-called "axis-line", draw directly next to the label, parallel to the label
Limitlines, which allows special information, such as boundaries or restrictions, to exist.
1. Controlshould be drawnwhich parts (axes)setenabled (Boolean enabled): Whether the axis is enabled, and if disabled, all properties on the axis settings are ignored
Setdrawlabels (Boolean enabled): whether to draw a label
Setdrawaxisline (Boolean enabled): Whether to draw axes
Setdrawgridlines (Boolean enabled): Whether and grid axes
2, modify the style of the axisSetTextColor (int color): Set axis label color
Settextsize (float size): Set axis label font size, unit DP
Settypeface (Typeface tf): Set axis label font
Setgridcolor (int color): Set grid color
Setgridlinewidth (float width): Sets the grid width.
Setaxislinecolor (int color): Set axis color
Setaxislinewidth (float width): Set axis width
Enablegriddashedline (float linelength, float spacelength, float phase): Make grid lines in dashed draw mode,
LineLength control line length, spacelength spacing between control lines, phase control starting point
3, Limitline classTwo-axis support, so-called Limitlines allows the display of special information such as boundaries or restrictions. The limitline is added to the yaxis while in the horizontal direction, and is added to the Xaxis in the vertical direction. This is how to add and remove Limitlines from the axis
Addlimitline (limitline L): Add a new limitline on the axis
Removelimitline (limitline L): removing limitline from the shaft
There is more to add/remove available methods.
Setdrawlimitlinesbehinddata (Boolean enabled): Allows control of the actual data order on the z-axis between limitlines. If set to True,limitlines is drawn behind the real data, otherwise on top. False by default
As its name limitline, it can be used to provide users with additional restrictions on information.
For example, your chart might show the results of a different yo user's blood pressure measurements. In order to inform users that the systolic pressure of more than 140 mmhg is considered a health risk, you can add a limitline 140 to provide this information.


YAxis leftAxis = chart.getAxisLeft();

LimitLine ll = new LimitLine(140f, "Critical Blood Pressure");
ll.setLineColor(Color.RED);
ll.setLineWidth(4f);
ll.setTextColor(Color.BLACK);
ll.setTextSize(12f);
// .. and more styling options

leftAxis.addLimitLine(ll);
Fourth. X-axis XaxisXaxis is a subclass of Axisbase.
The Xaxis class (in the 2.0.0 version contains the call), is the container for all data and information related to the horizontal axis: Xaxis shows what is handed to the ChartData object as a arraylist<string> or string[].
the Xaxis class allows you to customize the style and the following sections:
Horizontal alignment label drawing, which contains the axis description value, set for the data object provided for the x axis of the chart.
A "axis-line" is drawn parallel to the label next to the label.
The gridlines for each axis label in the vertical direction.
Get instance Method

Xaxis Xaxis = Chart.getxaxis ();
1. Value of custom axessetlabelstoskip (int count): Sets the number of labels that should be skipped before the next label is drawn on the axis. This disables the ability to automatically calculate space between axis labels, and sets the number of tags that are provided by the method to skip a fixed number of labels. Call Resetlabelstoskip (...). ) re-enable automatic calculation
Resetlabelstoskip (): Disables the number of custom tags that are skipped, automatically calculates the space between axis labels
Setavoidfirstlastclipping (Boolean enabled): If set to True, the label entries in the first and last axes of the edge of the chart or screen are clipped.
Setspacebetweenlabels (int characters): Set the excluded characters between the x-axis labels, the default space: 4.
SetPosition (xaxisposition POS): Where the x-axis should appear. The top bottom appears, the top, bottom, both_sided,top_inside or Bottom_inside are selected. 2. Formatted ValueSetvalueformatter (Xaxisvalueformatter Formatter): Dynamically set custom formats before drawing, details3. code example


XAxis xAxis = chart.getXAxis();
xAxis.setPosition(XAxisPosition.BOTTOM);
xAxis.setTextSize(10f);
xAxis.setTextColor(Color.RED);
xAxis.setDrawAxisLine(true);
xAxis.setDrawGridLines(false);
// set a custom value formatter
xAxis.setXValueFormatter(new MyCustomFormatter()); 
// and more...
Fifth, y axis yaxisYAxis is a subclass of Axisbase.
The YAxis class is a container of all data and information related to the vertical axis, related to the axis perpendicular to the right of the left. Radarchart has only one y-axis, and by default, the two axes of the icon are enabled for drawing.
1. How to obtain a y-axis instance


YAxis leftAxis = chart.getAxisLeft();
YAxis rightAxis = chart.getAxisRight();

YAxis leftAxis = chart.getAxis(AxisDependency.LEFT);

YAxis yAxis = radarChart.getYAxis(); // this method radarchart only
2. Value of custom axesSetaxismaxvalue (float max): Sets the maximum value of the axis. If set, this value is not automatically calculated based on the data provided.
Resetaxismaxvalue (): The maximum value is automatically calculated when you undo the maximum value set previously.
Setaxisminvalue (float min): Sets the minimum value of the axis. This setting will not be automatically calculated based on the data provided.
Resetaxisminvalue (): The minimum value is automatically calculated by undoing the minimum axis value set previously
Setstartatzero (Boolean enabled): Obsolete-using setaxisminvalue (...) or setaxismaxvalue (...)
Setinverted (Boolean enabled): Reverses the axis, if true, the maximum value is at the bottom and the top is the minimum value.
Setspacetop (float percent): Sets the top spacing of the highest position on the axis at the highest position in the table, as a percentage of the total axis.
Setspacebottom (float percent): sets the bottom spacing of the lowest position on the axis at the lowest position in the table, which represents the percentage of the total axis.
Setshowonlyminmax (Boolean enabled): If enabled, this axis line maximum and minimum values schema ignores the defined number of labels.
Setlabelcount (int count, Boolean Force): Sets the number of labels on the axis, not the exact value, which may cause uneven axes if forced setting
SetPosition (yaxislabelposition POS): Sets the axis drawing position. Either Inside_chart or Outside_chart.
Setgranularity (float gran): Set y-axis minimum interval
Setgranularityenabled (Boolean enabled): Whether y-axis minimum interval is enabled
you must set the property before setting the data to take effect. 3. Custom Label FormatSetvalueformatter (YAXISVALUEFORMATTERF): Sets a custom valueformatter on the axis. You can format the original label text and return a custom text. More
4,zeroline In addition to the grid lines, each value in the horizontal y-axis, has so-called zeroline, which is plotted on a 0-bit axis, is similar to a grid line but can be configured separately.



// data has AxisDependency.LEFT
YAxis left = mChart.getAxisLeft();
left.setDrawLabels(false); // no axis labels
left.setDrawAxisLine(false); // no axis line
left.setDrawGridLines(false); // no grid lines
left.setDrawZeroLine(true); // draw a zero line
mChart.getAxisRight().setEnabled(false); // no right axis

6. More Instance Code


YAxis yAxis = mChart.getAxisLeft();
yAxis.setTypeface(...); // set a different font
yAxis.setTextSize(12f); // set the textsize
yAxis.setAxisMaxValue(100f); // the axis maximum is 100
yAxis.setTextColor(Color.BLACK);
yAxis.setValueFormatter(new MyValueFormatter());
yAxis.setLabelCount(6, true); // force 6 labels
//... and more

Welcome to scan QR Code, follow public account



Android Open Source Chart library Mpandroidchart document translation (top)


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.