### Initializing Entry Lists in Java Source: https://github.com/philjay/mpandroidchart/wiki/Setting-Data Example of creating and initializing `ArrayList` objects to hold `Entry` objects for different datasets, such as company revenues over quarters. ```java List valsComp1 = new ArrayList(); List valsComp2 = new ArrayList(); ``` -------------------------------- ### Creating and Configuring LineDataSets in Java Source: https://github.com/philjay/mpandroidchart/wiki/Setting-Data Example of instantiating `LineDataSet` objects using the populated lists of `Entry` objects and assigning a label. It also demonstrates setting the axis dependency for each dataset. ```java LineDataSet setComp1 = new LineDataSet(valsComp1, "Company 1"); setComp1.setAxisDependency(AxisDependency.LEFT); LineDataSet setComp2 = new LineDataSet(valsComp2, "Company 2"); setComp2.setAxisDependency(AxisDependency.LEFT); ``` -------------------------------- ### Populate BarChart with BarEntry Data (Java) Source: https://github.com/philjay/mpandroidchart/wiki/Setting-Data Shows how to create and add `BarEntry` objects to a `BarDataSet` for a `BarChart`. This example includes creating entries with specific x-values and corresponding y-values, and demonstrates how gaps can be introduced. ```java List entries = new ArrayList<>(); entries.add(new BarEntry(0f, 30f)); entries.add(new BarEntry(1f, 80f)); entries.add(new BarEntry(2f, 60f)); entries.add(new BarEntry(3f, 50f)); // gap of 2f entries.add(new BarEntry(5f, 70f)); entries.add(new BarEntry(6f, 60f)); BarDataSet set = new BarDataSet(entries, "BarDataSet"); ``` -------------------------------- ### Entry Constructor in Java Source: https://github.com/philjay/mpandroidchart/wiki/Setting-Data Demonstrates the constructor for `Entry`, which is a fundamental data point wrapper in MPAndroidChart. Each `Entry` object holds a float x-value and a float y-value. ```java public Entry(float x, float y) { ... } ``` -------------------------------- ### BarChart Setup and Customization in Java Source: https://context7.com/philjay/mpandroidchart/llms.txt Demonstrates the complete setup of a BarChart in Android using Java. It covers configuring chart behavior, axes (X and Y), legend, creating bar entries, styling datasets, and displaying the chart. Dependencies include Android SDK components and MPAndroidChart library. ```java BarChart chart = findViewById(R.id.chart1); // Configure chart behavior chart.setDrawBarShadow(false); chart.setDrawValueAboveBar(true); chart.getDescription().setEnabled(false); chart.setMaxVisibleValueCount(60); chart.setPinchZoom(false); chart.setDrawGridBackground(false); // Configure X-Axis with custom date formatter XAxis xAxis = chart.getXAxis(); xAxis.setPosition(XAxisPosition.BOTTOM); xAxis.setDrawGridLines(false); xAxis.setGranularity(1f); xAxis.setLabelCount(7); xAxis.setValueFormatter(new IAxisValueFormatter() { @Override public String getFormattedValue(float value, AxisBase axis) { return String.format("Day %d", (int) value); } }); // Configure Y-Axes YAxis leftAxis = chart.getAxisLeft(); leftAxis.setLabelCount(8, false); leftAxis.setPosition(YAxisLabelPosition.OUTSIDE_CHART); leftAxis.setSpaceTop(15f); leftAxis.setAxisMinimum(0f); YAxis rightAxis = chart.getAxisRight(); rightAxis.setDrawGridLines(false); rightAxis.setLabelCount(8, false); // Configure legend Legend legend = chart.getLegend(); legend.setVerticalAlignment(Legend.LegendVerticalAlignment.BOTTOM); legend.setHorizontalAlignment(Legend.LegendHorizontalAlignment.LEFT); legend.setOrientation(Legend.LegendOrientation.HORIZONTAL); legend.setDrawInside(false); legend.setForm(LegendForm.SQUARE); legend.setFormSize(9f); // Create bar entries ArrayList entries = new ArrayList<>(); for (int i = 1; i <= 12; i++) { float value = (float) (Math.random() * 100); entries.add(new BarEntry(i, value)); } // Create and style dataset BarDataSet dataSet = new BarDataSet(entries, "Monthly Sales 2024"); dataSet.setDrawIcons(false); dataSet.setColors(ColorTemplate.MATERIAL_COLORS); // Create BarData and configure bar width BarData barData = new BarData(dataSet); barData.setValueTextSize(10f); barData.setBarWidth(0.9f); chart.setData(barData); chart.invalidate(); ``` -------------------------------- ### PieChart Setup and Customization in Java Source: https://context7.com/philjay/mpandroidchart/llms.txt Provides a comprehensive example of setting up a PieChart (or Donut Chart) in Android using Java. This includes enabling percentage values, configuring the center hole for a donut effect, setting center text with formatting, enabling rotation, creating pie entries, styling datasets, and applying animations. It requires Android SDK and MPAndroidChart library. ```java PieChart chart = findViewById(R.id.chart1); // Configure chart to use percentages chart.setUsePercentValues(true); chart.getDescription().setEnabled(false); chart.setExtraOffsets(5, 10, 5, 5); // Configure center area (donut effect) chart.setDrawHoleEnabled(true); chart.setHoleColor(Color.WHITE); chart.setHoleRadius(58f); chart.setTransparentCircleColor(Color.WHITE); chart.setTransparentCircleAlpha(110); chart.setTransparentCircleRadius(61f); // Set center text with formatting SpannableString centerText = new SpannableString("Sales\nDistribution"); centerText.setSpan(new RelativeSizeSpan(1.5f), 0, 5, 0); centerText.setSpan(new StyleSpan(Typeface.BOLD), 0, 5, 0); centerText.setSpan(new ForegroundColorSpan(Color.GRAY), 6, centerText.length(), 0); chart.setCenterText(centerText); chart.setDrawCenterText(true); // Enable rotation chart.setRotationAngle(0); chart.setRotationEnabled(true); chart.setHighlightPerTapEnabled(true); // Create pie entries (value, label, icon optional) ArrayList entries = new ArrayList<>(); entries.add(new PieEntry(40.5f, "Q1")); entries.add(new PieEntry(25.3f, "Q2")); entries.add(new PieEntry(18.7f, "Q3")); entries.add(new PieEntry(15.5f, "Q4")); // Create and style dataset PieDataSet dataSet = new PieDataSet(entries, "Quarterly Results"); dataSet.setSliceSpace(3f); dataSet.setSelectionShift(5f); // Add colors from predefined templates ArrayList colors = new ArrayList<>(); for (int c : ColorTemplate.VORDIPLOM_COLORS) colors.add(c); for (int c : ColorTemplate.JOYFUL_COLORS) colors.add(c); dataSet.setColors(colors); // Create PieData with percentage formatter PieData pieData = new PieData(dataSet); pieData.setValueFormatter(new PercentFormatter()); pieData.setValueTextSize(12f); pieData.setValueTextColor(Color.WHITE); chart.setData(pieData); // Configure legend Legend legend = chart.getLegend(); legend.setVerticalAlignment(Legend.LegendVerticalAlignment.TOP); legend.setHorizontalAlignment(Legend.LegendHorizontalAlignment.RIGHT); legend.setOrientation(Legend.LegendOrientation.VERTICAL); legend.setDrawInside(false); // Configure entry labels chart.setEntryLabelColor(Color.WHITE); chart.setEntryLabelTextSize(12f); // Animate with easing function chart.animateY(1400, Easing.EaseInOutQuad); chart.invalidate(); ``` -------------------------------- ### Initialize LineChart from XML in Java Source: https://github.com/philjay/mpandroidchart/wiki/Getting-Started This Java code demonstrates how to retrieve a LineChart instance that was previously defined in an XML layout file. It uses `findViewById` to get a reference to the chart by its ID. This is a standard practice in Android development to interact with UI elements defined in XML. ```java // in this example, a LineChart is initialized from xml LineChart chart = (LineChart) findViewById(R.id.chart); ``` -------------------------------- ### Create PieEntry Object (Java) Source: https://github.com/philjay/mpandroidchart/wiki/Setting-Data Demonstrates the constructor for creating a PieEntry object, which holds the value and label for a pie slice. The value determines the size of the slice, and the label provides a description. ```java public PieEntry(float value, String label) { ... } ``` -------------------------------- ### Populate and Display PieChart (Java) Source: https://github.com/philjay/mpandroidchart/wiki/Setting-Data Shows how to create a list of PieEntry objects, add them to a PieDataSet, then to a PieData object, and finally set this data to the PieChart for display. The PieChart is invalidated to refresh the view. ```java List entries = new ArrayList<>(); entries.add(new PieEntry(18.5f, "Green")); entries.add(new PieEntry(26.7f, "Yellow")); entries.add(new PieEntry(24.0f, "Red")); entries.add(new PieEntry(30.8f, "Blue")); PieDataSet set = new PieDataSet(entries, "Election Results"); PieData data = new PieData(set); pieChart.setData(data); pieChart.invalidate(); // refresh ``` -------------------------------- ### MPAndroidChart: Create Stacked Bar Chart Entry (Java) Source: https://github.com/philjay/mpandroidchart/wiki/Setting-Data This Java example shows how to create a single entry for a stacked BarChart in MPAndroidChart. It utilizes a specific BarEntry constructor that accepts an array of floats for the y-values, representing the different segments that form the stack of a single bar. ```java public BarEntry(float x, float [] yValues) { ... } BarEntry stackedEntry = new BarEntry(0f, new float[] { 10, 20, 30 }); ``` -------------------------------- ### IAxisValueFormatter Implementation for X-Axis Labels in Java Source: https://github.com/philjay/mpandroidchart/wiki/Setting-Data Provides an example of implementing the `IAxisValueFormatter` interface to customize the labels displayed on the X-axis. This allows for descriptive labels (like 'Q1', 'Q2') instead of raw numerical values. ```java // the labels that should be drawn on the XAxis final String[] quarters = new String[] { "Q1", "Q2", "Q3", "Q4" }; IAxisValueFormatter formatter = new IAxisValueFormatter() { @Override public String getFormattedValue(float value, AxisBase axis) { ``` -------------------------------- ### Maven Setup for MPAndroidChart Source: https://github.com/philjay/mpandroidchart/blob/master/README.md This snippet shows how to configure your Maven project to include the MPAndroidChart library. It requires adding the JitPack repository and specifying the library as a dependency in your pom.xml file. Ensure you use the correct version of the library. ```xml jitpack.io https://jitpack.io com.github.PhilJay MPAndroidChart v3.1.0 ``` -------------------------------- ### Gradle Setup for MPAndroidChart Source: https://github.com/philjay/mpandroidchart/blob/master/README.md This snippet demonstrates how to add the MPAndroidChart library to an Android project using Gradle. It includes configuring the JitPack repository and adding the library as a dependency. Ensure you have a stable internet connection for dependency resolution. ```gradle repositories { maven { url 'https://jitpack.io' } } dependencies { implementation 'com.github.PhilJay:MPAndroidChart:v3.1.0' } ``` -------------------------------- ### Full Legend Customization Example in Java Source: https://github.com/philjay/mpandroidchart/wiki/Legend An example demonstrating various legend customization options, including form size, form type, position, typeface, text size, text color, entry spacing, and setting custom labels and colors. ```java Legend l = chart.getLegend(); l.setFormSize(10f); // set the size of the legend forms/shapes l.setForm(LegendForm.CIRCLE); // set what type of form/shape should be used l.setPosition(LegendPosition.BELOW_CHART_LEFT); l.setTypeface(...); l.setTextSize(12f); l.setTextColor(Color.BLACK); l.setXEntrySpace(5f); // set the space between the legend entries on the x-axis l.setYEntrySpace(5f); // set the space between the legend entries on the y-axis // set custom labels and colors l.setCustom(ColorTemplate.VORDIPLOM_COLORS, new String[] { "Set1", "Set2", "Set3", "Set4", "Set5" }); ``` -------------------------------- ### LineDataSet Constructor in Java Source: https://github.com/philjay/mpandroidchart/wiki/Setting-Data Shows the constructor for `LineDataSet`, which represents a group of entries belonging together in a LineChart. It requires a list of `Entry` objects and a label string for identification and legend display. ```java public LineDataSet(List entries, String label) { ... } ``` -------------------------------- ### MPAndroidChart Gradle Integration - Project Setup Source: https://context7.com/philjay/mpandroidchart/llms.txt Integrates the MPAndroidChart library into an Android project by adding the necessary dependency to the Gradle build files. This ensures the library is available for use in your application. This snippet includes configurations for both project-level and module-level Gradle files. ```gradle // Project-level build.gradle buildscript { repositories { google() mavenCentral() } dependencies { classpath 'com.android.tools.build:gradle:7.0.4' } } allprojects { repositories { google() mavenCentral() maven { url 'https://jitpack.io' } } } // Module-level build.gradle (app/build.gradle) dependencies { implementation 'com.github.PhilJay:MPAndroidChart:v3.1.0' } ``` -------------------------------- ### Format Axis Values with IAxisValueFormatter (Java) Source: https://github.com/philjay/mpandroidchart/wiki/Setting-Data Implements the IAxisValueFormatter interface to define custom formatting for axis values in MPAndroidChart. This example sets the decimal digits to 0, indicating no decimal places are needed for the displayed numbers. ```java IAxisValueFormatter formatter = new IAxisValueFormatter() { @Override public String getFormattedValue(float value, AxisBase axis) { return String.valueOf((int)value); } // we don't draw numbers, so no decimal digits needed @Override public int getDecimalDigits() { return 0; } }; XAxis xAxis = mLineChart.getXAxis(); xAxis.setGranularity(1f); // minimum axis-step (interval) is 1 xAxis.setValueFormatter(formatter); ``` -------------------------------- ### Get XAxis Instance in Java Source: https://github.com/philjay/mpandroidchart/wiki/XAxis Acquires an instance of the XAxis class from a chart object. This is the starting point for customizing the horizontal axis in MPAndroidChart. ```java XAxis xAxis = chart.getXAxis(); ``` -------------------------------- ### LineData Constructors in Java Source: https://github.com/philjay/mpandroidchart/wiki/Setting-Data Illustrates the constructors for `LineData`, which is a subclass of `ChartData` used specifically for `LineChart`. It accepts a list of `ILineDataSet` objects or individual `ILineDataSet` objects. ```java /** List constructor */ public LineData(List sets) { ... } ``` ```java /** Constructor with one or multiple ILineDataSet objects */ public LineData(ILineDataSet...) { ... } ``` -------------------------------- ### Sort Entries for LineChart with EntryXComparator (Java) Source: https://github.com/philjay/mpandroidchart/wiki/Setting-Data Demonstrates how to sort a list of `Entry` objects in ascending order of their x-position using `EntryXComparator`. This is crucial for `LineChart` performance as the library relies on sorted data for binary search algorithms. ```java List entries = ...; Collections.sort(entries, new EntryXComparator()); ``` -------------------------------- ### Set BarChart Data and Styling (Java) Source: https://github.com/philjay/mpandroidchart/wiki/Setting-Data Illustrates how to create a `BarData` object from a `BarDataSet`, set custom bar width, enable bar fitting to the x-axis, and refresh the `BarChart`. This ensures all bars are visible and correctly scaled. ```java BarData data = new BarData(set); data.setBarWidth(0.9f); // set custom bar width chart.setData(data); chart.setFitBars(true); // make the x-axis fit exactly all bars chart.invalidate(); // refresh ``` -------------------------------- ### Populating Entry Objects in Java Source: https://github.com/philjay/mpandroidchart/wiki/Setting-Data Code snippet showing how to create individual `Entry` objects with specific x and y values and add them to the prepared lists. The x-value typically corresponds to the index on the x-axis (e.g., quarter number). ```java Entry c1e1 = new Entry(0f, 100000f); // 0 == quarter 1 valsComp1.add(c1e1); Entry c1e2 = new Entry(1f, 140000f); // 1 == quarter 2 ... valsComp1.add(c1e2); // and so on ... Entry c2e1 = new Entry(0f, 130000f); // 0 == quarter 1 valsComp2.add(c2e1); Entry c2e2 = new Entry(1f, 115000f); // 1 == quarter 2 ... valsComp2.add(c2e2); //... ``` -------------------------------- ### Custom MarkerView Implementation (Java) Source: https://github.com/philjay/mpandroidchart/wiki/MarkerView A detailed Java implementation of a custom `MarkerView`. This example shows how to initialize a `TextView`, refresh its content based on the highlighted `Entry`, and customize the marker's offset for positioning. ```java public class CustomMarkerView extends MarkerView { private TextView tvContent; public CustomMarkerView (Context context, int layoutResource) { super(context, layoutResource); // this markerview only displays a textview tvContent = (TextView) findViewById(R.id.tvContent); } // callbacks everytime the MarkerView is redrawn, can be used to update the // content (user-interface) @Override public void refreshContent(Entry e, Highlight highlight) { tvContent.setText("" + e.getVal()); // set the entry-value as the display text } @Override public int getXOffset(float xpos) { // this will center the marker-view horizontally return -(getWidth() / 2); } @Override public int getYOffset(float ypos) { // this will cause the marker-view to be above the selected value return -getHeight(); } } ``` -------------------------------- ### Base ChartData Class Example (Java) Source: https://github.com/philjay/mpandroidchart/wiki/The-ChartData-class Illustrates the declaration of a LineData class extending the base ChartData class. This serves as a foundation for various chart data types. ```java public class LineData extends ChartData { ... } ``` -------------------------------- ### MPAndroidChart: Create Grouped Bar Chart Data (Java) Source: https://github.com/philjay/mpandroidchart/wiki/Setting-Data This code snippet demonstrates how to prepare data for a grouped BarChart in MPAndroidChart. It involves creating lists of BarEntry objects for each group and then initializing BarDataSet objects. The grouping is handled by the library. ```java YourData[] group1 = ...; YourData[] group2 = ...; List entriesGroup1 = new ArrayList<>(); List entriesGroup2 = new ArrayList<>(); // fill the lists for(int i = 0; i < group1.length; i++) { entriesGroup1.add(new BarEntry(i, group1.getValue())); entriesGroup2.add(new BarEntry(i, group2.getValue())); } BarDataSet set1 = new BarDataSet(entriesGroup1, "Group 1"); BarDataSet set2 = new BarDataSet(entriesGroup2, "Group 2"); ``` -------------------------------- ### Create LineChart Programmatically in Java Source: https://github.com/philjay/mpandroidchart/wiki/Getting-Started This Java code shows how to create a LineChart instance dynamically in code. After creating the chart object, it needs to be added to an existing layout, such as a RelativeLayout, to be displayed on the screen. This provides flexibility in chart placement and management. ```java // 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 ``` -------------------------------- ### Assembling ChartData and Refreshing Chart in Java Source: https://github.com/philjay/mpandroidchart/wiki/Setting-Data Illustrates the final steps of creating a `LineData` object by adding the configured `LineDataSet` objects to a list of `ILineDataSet`. The `LineData` is then set to the `LineChart`, and `invalidate()` is called to refresh the chart view. ```java // use the interface ILineDataSet List dataSets = new ArrayList(); dataSets.add(setComp1); dataSets.add(setComp2); LineData data = new LineData(dataSets); mLineChart.setData(data); mLineChart.invalidate(); // refresh ``` -------------------------------- ### Create and Style LineDataSet in Java Source: https://github.com/philjay/mpandroidchart/wiki/Getting-Started This Java code shows how to create a `LineDataSet` from a list of `Entry` objects. A DataSet groups related data points and allows for individual styling, such as setting the color of the data line and the text color for values. The 'Label' parameter is used for legend display. ```java LineDataSet dataSet = new LineDataSet(entries, "Label"); // add entries to dataset dataSet.setColor(...); dataSet.setValueTextColor(...); // styling, ... ``` -------------------------------- ### Acquire YAxis Instance (Java) Source: https://github.com/philjay/mpandroidchart/wiki/YAxis Demonstrates how to obtain YAxis objects for different chart types. You can get the left or right YAxis, specify the dependency, or retrieve the YAxis for a RadarChart. ```java YAxis leftAxis = chart.getAxisLeft(); YAxis rightAxis = chart.getAxisRight(); YAxis leftAxis = chart.getAxis(AxisDependency.LEFT); YAxis yAxis = radarChart.getYAxis(); // this method radarchart only ``` -------------------------------- ### Setting Chart Data with ChartData in Java Source: https://github.com/philjay/mpandroidchart/wiki/Setting-Data The `setData` method is used to provide data to any chart. The `ChartData` class and its subclasses (like `LineData`) encapsulate all necessary information for rendering. Data is typically provided as a list of `IDataSet` objects. ```java public void setData(ChartData data) { ... } ``` -------------------------------- ### Convert Data to Chart Entries in Java Source: https://github.com/philjay/mpandroidchart/wiki/Getting-Started This Java snippet illustrates how to convert custom data objects into `Entry` objects, which are required by MPAndroidChart. Each `Entry` represents a point on the chart with an x and y coordinate. This is a crucial step before adding data to a DataSet. ```java YourData[] dataObjects = ...; List entries = new ArrayList(); for (YourData data : dataObjects) { // turn your data into Entry objects entries.add(new Entry(data.getValueX(), data.getValueY())); } ``` -------------------------------- ### Commit Message Style Guide for MPAndroidChart Source: https://github.com/philjay/mpandroidchart/blob/master/CONTRIBUTING.md Defines the structure and constraints for writing commit messages when contributing to the MPAndroidChart project. It specifies a character limit for the title and recommendations for the body content, including line wrapping. ```text The commit title CANNOT exceed 50 characters The body of the message comes after an empty new line, and describes the changes more thoroughly. If the change is obvious and self-explanatory from the title, you can omit the body. You should describe all changes if many were made, or maybe some trickery that only code wizards can understand. Be polite and wrap your lines to 72 characters, but if you prefer going to 100 characters then I guess we can't stop you. ``` -------------------------------- ### Setting and Getting Marker on Chart (Java) Source: https://github.com/philjay/mpandroidchart/wiki/IMarker-Interface Demonstrates how to set a custom `IMarker` implementation to an MPAndroidChart instance using `setMarker(...)` and how to retrieve the currently set marker using `getMarker(...)`. ```java IMarker marker = new YourMarkerView(); chart.setMarker(marker); ``` ```java IMarker marker = chart.getMarker(); ``` -------------------------------- ### Define LineChart View in XML Source: https://github.com/philjay/mpandroidchart/wiki/Getting-Started This snippet shows how to declare a LineChart within an XML layout file. It sets the width and height of the chart to fill its parent container. This is a common way to integrate charts into Android applications. ```xml ``` -------------------------------- ### Custom MarkerView Layout (XML) Source: https://github.com/philjay/mpandroidchart/wiki/MarkerView An example XML layout for a custom `MarkerView`. This layout defines a `RelativeLayout` containing a `TextView` that will display the chart entry's value. The background and styling can be customized as needed. ```xml ``` -------------------------------- ### Custom MarkerView Implementation (Java) Source: https://github.com/philjay/mpandroidchart/wiki/IMarker-Interface Example of creating a custom marker view by extending `MarkerView` and implementing the `IMarker` interface. It shows how to find layout components, set text content based on chart entries, and define the marker's offset. ```java public class YourMarkerView extends MarkerView { private TextView tvContent; public MyMarkerView(Context context, int layoutResource) { super(context, layoutResource); // find your layout components tvContent = (TextView) findViewById(R.id.tvContent); } // callbacks everytime the MarkerView is redrawn, can be used to update the // content (user-interface) @Override public void refreshContent(Entry e, Highlight highlight) { tvContent.setText("" + e.getY()); // this will perform necessary layouting super.refreshContent(e, highlight); } private MPPointF mOffset; @Override public MPPointF getOffset() { if(mOffset == null) { // center the marker horizontally and vertically mOffset = new MPPointF(-(getWidth() / 2), -getHeight()); } return mOffset; } } ``` -------------------------------- ### Get ViewPortHandler Instance in Java Source: https://github.com/philjay/mpandroidchart/wiki/The-ViewPortHandler This snippet demonstrates how to obtain an instance of the ViewPortHandler from a chart object in Java. The ViewPortHandler manages the chart's view-port properties such as zoom and translation. ```java ViewPortHandler handler = chart.getViewPortHandler(); ``` -------------------------------- ### Configure and Draw Zero Line (Java) Source: https://github.com/philjay/mpandroidchart/wiki/YAxis Provides an example of how to enable and customize the zero-line on the YAxis. This code disables other axis elements like labels and grid lines to highlight the zero-line. ```java // 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 ``` -------------------------------- ### Getting and Checking Data Methods in ChartData (Java) Source: https://github.com/philjay/mpandroidchart/wiki/The-ChartData-class Shows getter and convenience methods in ChartData for retrieving a DataSet by index and checking for the existence of an Entry or a DataSet. Note the performance warning for the `contains(Entry)` method. ```java public DataSet getDataSetByIndex(int index) { // Implementation details } public boolean contains(Entry entry) { // Implementation details - performance warning applies } public boolean contains(T dataSet) { // Implementation details } ``` -------------------------------- ### MPAndroidChart: Apply Grouping and Styling to Bar Chart (Java) Source: https://github.com/philjay/mpandroidchart/wiki/Setting-Data This snippet shows how to configure and apply grouping to a BarChart in MPAndroidChart. It sets bar width, creates a BarData object, adds the datasets, and then uses the `groupBars` method to arrange them. Finally, it invalidates the chart to refresh the view. ```java float groupSpace = 0.06f; float barSpace = 0.02f; // x2 dataset float barWidth = 0.45f; // x2 dataset // (0.02 + 0.45) * 2 + 0.06 = 1.00 -> interval per "group" BarData data = new BarData(set1, set2); data.setBarWidth(barWidth); // set the width of each bar barChart.setData(data); barChart.groupBars(1980f, groupSpace, barSpace); // perform the "explicit" grouping barChart.invalidate(); // refresh ``` -------------------------------- ### Set Data to Chart and Invalidate in Java Source: https://github.com/philjay/mpandroidchart/wiki/Getting-Started This Java snippet demonstrates the final steps in adding data to an MPAndroidChart. A `LineData` object is created using the `LineDataSet`, then set to the chart instance. Finally, `chart.invalidate()` is called to refresh the chart's display with the new data. ```java LineData lineData = new LineData(dataSet); chart.setData(lineData); chart.invalidate(); // refresh ``` -------------------------------- ### Combined Chart: Integrating Multiple Chart Types (Java) Source: https://context7.com/philjay/mpandroidchart/llms.txt This example shows how to create a CombinedChart, which allows multiple chart types (like line and bar) to be displayed simultaneously. It covers setting up the chart, configuring axes, creating separate datasets for line and bar data, combining them into a single data object, and rendering the chart. Uses Math.random() for data generation. ```java // CombinedChart with line and bar data CombinedChart chart = findViewById(R.id.chart1); chart.getDescription().setEnabled(false); chart.setBackgroundColor(Color.WHITE); chart.setDrawGridBackground(false); chart.setDrawBarShadow(false); chart.setHighlightFullBarEnabled(false); chart.setTouchEnabled(true); chart.setDragEnabled(true); chart.setScaleEnabled(true); // Configure axes XAxis xAxis = chart.getXAxis(); xAxis.setPosition(XAxisPosition.BOTTOM); xAxis.setGranularity(1f); YAxis leftAxis = chart.getAxisLeft(); leftAxis.setDrawGridLines(true); chart.getAxisRight().setEnabled(false); // Create combined data CombinedData combinedData = new CombinedData(); // Add line data ArrayList lineEntries = new ArrayList<>(); for (int i = 0; i < 12; i++) { lineEntries.add(new Entry(i, (float) (Math.random() * 50) + 50)); } LineDataSet lineDataSet = new LineDataSet(lineEntries, "Target"); lineDataSet.setColor(Color.RED); lineDataSet.setLineWidth(2.5f); lineDataSet.setCircleRadius(4f); lineDataSet.setDrawValues(false); combinedData.setData(new LineData(lineDataSet)); // Add bar data ArrayList barEntries = new ArrayList<>(); for (int i = 0; i < 12; i++) { barEntries.add(new BarEntry(i, (float) (Math.random() * 50) + 30)); } BarDataSet barDataSet = new BarDataSet(barEntries, "Actual"); barDataSet.setColor(Color.rgb(60, 220, 78)); combinedData.setData(new BarData(barDataSet)); chart.setData(combinedData); chart.invalidate(); ``` -------------------------------- ### XML Layout for MPAndroidChart Views Source: https://context7.com/philjay/mpandroidchart/llms.txt Defines different types of charts (LineChart, BarChart, PieChart) within an Android XML layout file. This allows for declarative setup of chart views, which can then be programmatically customized. The views are configured with basic layout parameters and IDs. ```xml ``` -------------------------------- ### MPAndroidChart: Center XAxis Labels for Grouped Bar Chart (Java) Source: https://github.com/philjay/mpandroidchart/wiki/Setting-Data This Java code snippet demonstrates how to center the XAxis labels above the groups of bars in an MPAndroidChart BarChart. This ensures that labels align correctly with their corresponding bar groups, enhancing readability. ```java XAxis xAxis = chart.getXAxis(); xAxis.setCenterAxisLabels(true); ``` -------------------------------- ### Apply Custom Value Formatter (Java) - MPAndroidChart Source: https://github.com/philjay/mpandroidchart/wiki/The-ValueFormatter-interface These Java code snippets show how to apply a custom `IValueFormatter` in MPAndroidChart. The examples illustrate two common use cases: setting the formatter for an entire `ChartData` object or applying it to a specific `DataSet` object. ```java // usage on whole data object lineData.setValueFormatter(new MyValueFormatter()); ``` ```java // usage on individual dataset object lineDataSet.setValueFormatter(new MyValueFormatter()); ``` -------------------------------- ### Implement Chart Gesture Callbacks in Java Source: https://github.com/philjay/mpandroidchart/wiki/Interaction-with-the-Chart This Java interface defines callback methods for various touch gestures performed on an MPAndroidChart. Implement this interface in your activity or fragment to receive notifications for chart events like gestures starting and ending, long presses, double-taps, single-taps, flings, scaling, and translation. ```java 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); } ``` -------------------------------- ### Get Legend Object in Java Source: https://github.com/philjay/mpandroidchart/wiki/Legend Retrieves the Legend object from the chart to allow for further customization. This is the starting point for all legend modifications. ```java Legend legend = chart.getLegend(); ``` -------------------------------- ### Add/Remove Data Dynamically in MPAndroidChart (Java) Source: https://github.com/philjay/mpandroidchart/wiki/Dynamic-&-Realtime-Data Demonstrates Java code examples for adding and removing data dynamically from MPAndroidChart. This involves using methods like `addEntry` and `removeEntry` on `DataSet` and `ChartData` objects, followed by `notifyDataSetChanged()` and `invalidate()` to refresh the chart. Note that specific `Entry` or `DataSet` objects and their indices are required for removal operations. ```java // EXAMPLE 1 // add entries to the "data" object exampleData.addEntry(...); chart.notifyDataSetChanged(); // let the chart know it's data changed chart.invalidate(); // refresh // EXAMPLE 2 // add entries to "dataSet" object dataSet.addEntry(...); exampleData.notifyDataChanged(); // let the data know a dataSet changed chart.notifyDataSetChanged(); // let the chart know it's data changed chart.invalidate(); // refresh ``` -------------------------------- ### Viewport Manipulation Example (Java) Source: https://github.com/philjay/mpandroidchart/wiki/Modifying-the-Viewport Demonstrates setting maximum visible range on the x-axis and moving the chart's view to a specific x-index. This example assumes data has already been set on the chart. The moveViewToX method automatically calls invalidate(). ```Java chart.setData(...); // first set data // now modify viewport chart.setVisibleXRangeMaximum(20); // allow 20 values to be displayed at once on the x-axis, not more chart.moveViewToX(10); // set the left edge of the chart to x-index 10 // moveViewToX(...) also calls invalidate() ``` -------------------------------- ### Configure LineChart with Filled Area and Limit Lines Source: https://context7.com/philjay/mpandroidchart/llms.txt This snippet demonstrates how to set up a LineChart in an Android application. It covers basic chart configuration, axis customization with limit lines, data entry creation, dataset styling, enabling a filled area under the line, and animating the chart. Dependencies include AndroidX Core, MPAndroidChart library, and potentially custom drawables for fill effects. ```java LineChart chart = findViewById(R.id.chart1); // Configure chart appearance and interactions chart.setBackgroundColor(Color.WHITE); chart.getDescription().setEnabled(false); chart.setTouchEnabled(true); chart.setDragEnabled(true); chart.setScaleEnabled(true); chart.setPinchZoom(true); // Configure X-Axis with dashed grid lines XAxis xAxis = chart.getXAxis(); xAxis.enableGridDashedLine(10f, 10f, 0f); xAxis.setPosition(XAxisPosition.BOTTOM); // Configure Y-Axis with range and limit lines YAxis yAxis = chart.getAxisLeft(); chart.getAxisRight().setEnabled(false); yAxis.enableGridDashedLine(10f, 10f, 0f); yAxis.setAxisMaximum(200f); yAxis.setAxisMinimum(-50f); // Add limit line for threshold visualization LimitLine limitLine = new LimitLine(150f, "Upper Limit"); limitLine.setLineWidth(4f); limitLine.enableDashedLine(10f, 10f, 0f); limitLine.setLabelPosition(LimitLabelPosition.RIGHT_TOP); yAxis.addLimitLine(limitLine); // Create data entries (x, y coordinates) ArrayList values = new ArrayList<>(); for (int i = 0; i < 45; i++) { float val = (float) (Math.random() * 180) - 30; values.add(new Entry(i, val)); } // Create and style dataset LineDataSet dataSet = new LineDataSet(values, "Temperature Data"); dataSet.setColor(Color.BLUE); dataSet.setCircleColor(Color.BLUE); dataSet.setLineWidth(2f); dataSet.setCircleRadius(4f); dataSet.setDrawCircleHole(false); dataSet.setValueTextSize(10f); // Enable filled area under line dataSet.setDrawFilled(true); dataSet.setFillDrawable(ContextCompat.getDrawable(this, R.drawable.fade_blue)); // Create LineData and set to chart LineData lineData = new LineData(dataSet); chart.setData(lineData); // Animate chart appearance chart.animateX(1500); chart.invalidate(); ``` -------------------------------- ### Highlight Class Constructors (Java) Source: https://github.com/philjay/mpandroidchart/wiki/Highlighting Provides constructors for the Highlight class, used to represent highlighted entries. These constructors allow creation of Highlight objects for standard entries and stacked BarEntries, facilitating programmatic highlighting. ```java /** constructor for standard highlight */ public Highlight(float x, int dataSetIndex) { ... } /** constructor for stacked BarEntry highlight */ public Highlight(float x, int dataSetIndex, int stackIndex) { ... } ``` -------------------------------- ### Bubble Chart: Visualizing Three-Dimensional Data Points (Java) Source: https://context7.com/philjay/mpandroidchart/llms.txt This code snippet illustrates the creation of a BubbleChart, where the size of each bubble represents a third data dimension. It covers chart initialization, axis configuration, generating bubble entries with x, y, and size values, and styling the dataset. Dependencies include ColorTemplate. ```java // BubbleChart with sized bubbles BubbleChart chart = findViewById(R.id.chart1); chart.getDescription().setEnabled(false); chart.setTouchEnabled(true); chart.setDragEnabled(true); chart.setScaleEnabled(true); chart.setPinchZoom(true); // Configure axes XAxis xAxis = chart.getXAxis(); xAxis.setPosition(XAxisPosition.BOTTOM); YAxis leftAxis = chart.getAxisLeft(); leftAxis.setAxisMinimum(0f); chart.getAxisRight().setEnabled(false); // Create bubble entries (x, y, size) ArrayList entries = new ArrayList<>(); entries.add(new BubbleEntry(1, 20, 4)); // size 4 entries.add(new BubbleEntry(2, 35, 8)); // size 8 entries.add(new BubbleEntry(3, 55, 6)); // size 6 entries.add(new BubbleEntry(4, 40, 10)); // size 10 entries.add(new BubbleEntry(5, 65, 5)); // size 5 // Create and style dataset BubbleDataSet dataSet = new BubbleDataSet(entries, "Market Share"); dataSet.setColors(ColorTemplate.COLORFUL_COLORS); dataSet.setValueTextSize(10f); BubbleData bubbleData = new BubbleData(dataSet); bubbleData.setValueTextSize(8f); chart.setData(bubbleData); chart.animateXY(1500, 1500); chart.invalidate(); ``` -------------------------------- ### Set Custom MarkerView to Chart (Java) Source: https://github.com/philjay/mpandroidchart/wiki/MarkerView This Java snippet shows how to instantiate a custom `MarkerView` with a specified layout resource and then set it to the MPAndroidChart instance using `setMarkerView()`. ```java CustomMarkerView mv = new CustomMarkerView(Context, R.layout.custom_marker_view_layout); // set the marker to the chart chart.setMarkerView(mv); ``` -------------------------------- ### MPAndroidChart DataSet Color Setting Methods (Java) Source: https://github.com/philjay/mpandroidchart/wiki/Setting-Colors Provides an overview of the various methods available on the DataSet class for configuring colors, including options for multiple colors, single colors, and using pre-defined color templates. It highlights the internal color resolution mechanisms. ```java // Sets colors using resource IDs, resolved internally by the chart library. // Colors are reused if the number of entries exceeds the number of provided colors. setComp1.setColors(new int[] { R.color.red1, R.color.red2, R.color.red3, R.color.red4 }, Context); // Sets colors using pre-resolved color integers (e.g., from getResources().getColor()). // Colors are reused if the number of entries exceeds the number of provided colors. setComp2.setColors(new int[] { color1, color2, color3, color4 }); // Sets colors using an ArrayList of pre-resolved color integers. // Colors are reused if the number of entries exceeds the number of provided colors. ArrayList colorList = new ArrayList<>(); colorList.add(colorA); colorList.add(colorB); dataSet.setColors(colorList); // Sets a single color for the entire DataSet. // This internally creates a new color array with the specified color. dataSet.setColor(R.color.blue); ``` -------------------------------- ### Dynamic Data Updates - Real-time Chart Updates Source: https://context7.com/philjay/mpandroidchart/llms.txt Updates chart data dynamically for real-time applications. This pattern demonstrates how to add new data entries, manage the dataset size, and notify the chart of changes to reflect live data updates. It includes using a `Handler` to periodically update the chart and auto-scrolling to the latest data points. ```java // Dynamic data update pattern LineChart chart = findViewById(R.id.chart1); // Initial setup chart.setTouchEnabled(true); chart.setDragEnabled(true); chart.setScaleEnabled(true); ArrayList entries = new ArrayList<>(); LineDataSet dataSet = new LineDataSet(entries, "Live Data"); dataSet.setColor(Color.BLUE); LineData lineData = new LineData(dataSet); chart.setData(lineData); // Update data periodically (e.g., every second) Handler handler = new Handler(); Runnable runnable = new Runnable() { private int xValue = 0; @Override public void run() { // Add new entry float newValue = (float) (Math.random() * 100); dataSet.addEntry(new Entry(xValue++, newValue)); // Keep only last 50 points if (dataSet.getEntryCount() > 50) { dataSet.removeFirst(); // Adjust x values for (int i = 0; i < dataSet.getEntryCount(); i++) { Entry entry = dataSet.getEntryForIndex(i); entry.setX(i); } } // Notify chart of data changes lineData.notifyDataChanged(); chart.notifyDataSetChanged(); // Auto-scroll to show latest data chart.setVisibleXRangeMaximum(50); chart.moveViewToX(lineData.getEntryCount()); // Repeat handler.postDelayed(this, 1000); } }; handler.post(runnable); ``` -------------------------------- ### Candlestick Chart: Financial OHLC Data Visualization (Java) Source: https://context7.com/philjay/mpandroidchart/llms.txt This snippet demonstrates how to create a CandleStickChart for displaying financial Open, High, Low, and Close (OHLC) data. It includes configuration for axes, creating candle entries, and styling the dataset. Dependencies include Color and Paint classes. ```java // CandleStickChart for financial data CandleStickChart chart = findViewById(R.id.chart1); chart.setBackgroundColor(Color.WHITE); chart.getDescription().setEnabled(false); chart.setDrawGridBackground(false); chart.setTouchEnabled(true); chart.setDragEnabled(true); chart.setScaleEnabled(true); // Configure axes XAxis xAxis = chart.getXAxis(); xAxis.setPosition(XAxisPosition.BOTTOM); xAxis.setDrawGridLines(false); YAxis leftAxis = chart.getAxisLeft(); leftAxis.setDrawGridLines(true); chart.getAxisRight().setEnabled(false); // Create candle entries (x, shadowHigh, shadowLow, open, close) ArrayList entries = new ArrayList<>(); entries.add(new CandleEntry(1, 115.0f, 110.0f, 112.0f, 113.5f)); entries.add(new CandleEntry(2, 117.0f, 113.0f, 113.5f, 116.0f)); entries.add(new CandleEntry(3, 118.0f, 114.0f, 116.0f, 115.0f)); entries.add(new CandleEntry(4, 120.0f, 115.0f, 115.0f, 119.0f)); entries.add(new CandleEntry(5, 121.0f, 117.0f, 119.0f, 118.0f)); // Create and style dataset CandleDataSet dataSet = new CandleDataSet(entries, "Stock Price"); dataSet.setDrawIcons(false); dataSet.setShadowColor(Color.DKGRAY); dataSet.setShadowWidth(0.7f); dataSet.setDecreasingColor(Color.RED); dataSet.setDecreasingPaintStyle(Paint.Style.FILL); dataSet.setIncreasingColor(Color.rgb(122, 242, 84)); dataSet.setIncreasingPaintStyle(Paint.Style.STROKE); dataSet.setNeutralColor(Color.BLUE); CandleData candleData = new CandleData(dataSet); chart.setData(candleData); chart.invalidate(); ```