private void refreshWeekBeforeSteps( DBHandler db, BarLineChartBase barChart, Calendar day, GBDevice device) { ActivityAnalysis analysis = new ActivityAnalysis(); day = (Calendar) day.clone(); // do not modify the caller's argument day.add(Calendar.DATE, -7); List<BarEntry> entries = new ArrayList<>(); List<String> labels = new ArrayList<>(); for (int counter = 0; counter < 7; counter++) { entries.add( new BarEntry(analysis.calculateTotalSteps(getSamplesOfDay(db, day, device)), counter)); labels.add(day.getDisplayName(Calendar.DAY_OF_WEEK, Calendar.SHORT, mLocale)); day.add(Calendar.DATE, 1); } BarDataSet set = new BarDataSet(entries, ""); set.setColor(akActivity.color); BarData data = new BarData(labels, set); data.setValueTextColor( Color .GRAY); // prevent tearing other graph elements with the black text. Another approach // would be to hide the values cmpletely with data.setDrawValues(false); LimitLine target = new LimitLine(mTargetSteps); barChart.getAxisLeft().getLimitLines().clear(); barChart.getAxisLeft().addLimitLine(target); setupLegend(barChart); barChart.setData(data); barChart.getLegend().setEnabled(false); }
private void addData() { ArrayList<BarEntry> yVals1 = new ArrayList<BarEntry>(); for (int i = 0; i < yData.length; i++) yVals1.add(new BarEntry(yData[i], i)); ArrayList<String> xVals = new ArrayList<String>(); for (int i = 0; i < xData.length; i++) xVals.add(xData[i]); // create pie data set BarDataSet dataSet = new BarDataSet(yVals1, "Stock"); // dataSet.setSliceSpace(5); // dataSet.setSelectionShift(5); // add many colors ArrayList<Integer> colors = new ArrayList<Integer>(); colors.add(Color.rgb(0, 204, 68)); colors.add(Color.rgb(230, 0, 0)); dataSet.setColors(colors); // instantiate pie data object BarData data = new BarData(xVals, dataSet); data.setValueTextSize(16); data.setValueTextColor(Color.BLACK); mChart.setData(data); // undo highlights mChart.highlightValue(null); // update pie chart mChart.invalidate(); }
private void createChart(View v) { BarChart chart = (BarChart) v.findViewById(R.id.barChart); chart.clear(); PSDatePickerView datePickerView = (PSDatePickerView) v.findViewById(R.id.date_picker_view); PSUserDataCollection dataCollection = PSDataStore.getInstance().getUserDataCollection(); ArrayList<BarEntry> entriesAgg = new ArrayList<BarEntry>(); ArrayList<String> xVals = new ArrayList<String>(); int idx = 0; for (Calendar cur = (Calendar) datePickerView.getStartDate().clone(); PSUtil.beforeCalender(cur, datePickerView.getEndDate()); cur.add(Calendar.DATE, 1)) { PSDailyData dailyData = dataCollection.getDailyData(cur.getTimeInMillis()); BarEntry ent = null; if (dailyData != null) { ent = new BarEntry(dailyData.getFormula(), idx, dailyData); } if (ent != null) { entriesAgg.add(ent); } xVals.add(PSUtil.weekDays[idx]); idx++; } BarDataSet setAgg = new BarDataSet(entriesAgg, PSDataStore.getInstance().getUser().getName()); setAgg.setAxisDependency(YAxis.AxisDependency.LEFT); setAgg.setColor(getResources().getColor(R.color.ps_blue_sky)); ArrayList<BarDataSet> dataSets = new ArrayList<BarDataSet>(); dataSets.add(setAgg); // BarData BarData data = new BarData(xVals, dataSets); chart.setData(data); // Config chart chart.setDescription(""); chart.setDrawHighlightArrow(true); // Config axises YAxis leftAxis = chart.getAxisLeft(); YAxis rightAxis = chart.getAxisRight(); leftAxis.setDrawGridLines(false); rightAxis.setDrawGridLines(false); // Config limit line LimitLine ll = new LimitLine(60f); ll.setLineColor(Color.CYAN); ll.setLineWidth(1f); leftAxis.removeAllLimitLines(); leftAxis.addLimitLine(ll); // Config marker PSDailyDataMarkerView markerView = new PSDailyDataMarkerView(v.getContext(), R.layout.ps_daily_data_marker_view); chart.setMarkerView(markerView); // Legend Legend l = chart.getLegend(); l.setEnabled(false); // Show data chart.animateY(600); }
private void setData(int count, float range) { ArrayList<String> xVals = new ArrayList<String>(); for (int i = 0; i < count; i++) { xVals.add(mMonths[i % 12]); } ArrayList<BarEntry> yVals1 = new ArrayList<BarEntry>(); for (int i = 0; i < count; i++) { Calendar calendar = Calendar.getInstance(); int year = calendar.get(Calendar.YEAR); int month = calendar.get(Calendar.MONTH); int day = calendar.get(Calendar.DAY_OF_MONTH); calendar.set(year, month, day, 2 * i, 0, 0); Long nowTime = calendar.getTime().getTime(); calendar.set(year, month, day, 2 * (i + 1), 0, 0); Long nextTime = calendar.getTime().getTime(); // 数据库查询 Float val; List<State> states = cupboard() .withDatabase(db) .query(State.class) .withSelection( "time_point > ? AND time_point < ?", nowTime.toString(), nextTime.toString()) .list(); if (states.isEmpty()) { val = 0.0f; } else if (states.size() == 1) { val = 0.0f; } else { State firstState = states.get(0); State lastState = states.get(states.size() - 1); val = Float.parseFloat(lastState.getVentilation_volume()) - Float.parseFloat(firstState.getVentilation_volume()); } yVals1.add(new BarEntry(val, i)); } BarDataSet set1 = new BarDataSet(yVals1, "单位时间吸入的空气量"); set1.setBarSpacePercent(35f); ArrayList<BarDataSet> dataSets = new ArrayList<BarDataSet>(); dataSets.add(set1); BarData data = new BarData(xVals, dataSets); data.setValueTextSize(10f); data.setValueTypeface(mTf); mChart.setData(data); }
@Override public View onCreateView( LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View rootview = inflater.inflate(R.layout.fragment_graph, container, false); chart = (BarChart) rootview.findViewById(R.id.chart); String url = "http://codez.savonia.fi/etp4301_2015_r1/Test.php?key=SK1-tekuenergy&Tags=4096&obj=OPI-JKL02&Date=2015-10-31&measuresInHour=12&graphScaleInHours=24&dataPrecision=hour&roundPrecision=2"; // String url = // "http://codez.savonia.fi/etp4301_2015_r1/Test.php?key=SK101-kuopioenergy&Tags=666&Date=2014-9-23&obj=KPOE&measuresInHour=1&graphScaleInHours=24&dataPrecision=hour&roundPrecision=2"; WebService request = new WebService(GraphActivityFragment.this, "GET"); Measurements = new ArrayList<BarEntry>(); dataSets = new ArrayList<BarDataSet>(); BarDataSet setComp1 = new BarDataSet(Measurements, "Sähkötolpat"); setComp1.setAxisDependency(YAxis.AxisDependency.LEFT); chart.setAutoScaleMinMaxEnabled(true); chart.setDrawValueAboveBar(false); xVals = new ArrayList<String>(); xVals.add("00:00"); xVals.add("01:00"); xVals.add("02:00"); xVals.add("03:00"); xVals.add("04:00"); xVals.add("05:00"); xVals.add("06:00"); xVals.add("07:00"); xVals.add("08:00"); xVals.add("09:00"); xVals.add("10:00"); xVals.add("11:00"); xVals.add("12:00"); xVals.add("13:00"); xVals.add("14:00"); xVals.add("15:00"); xVals.add("16:00"); xVals.add("17:00"); xVals.add("18:00"); xVals.add("19:00"); xVals.add("20:00"); xVals.add("21:00"); xVals.add("22:00"); xVals.add("23:00"); xVals.add("24:00"); request.execute(url); return rootview; }
private void setChartData(ClimbingArea ClimbingArea) { HashMap<Integer, Integer> difficultyMap = new HashMap<>(); for (int i = AppConstants.MIN_UIAA_LEVEL; i <= AppConstants.MAX_UIAA_LEVEL; ++i) { difficultyMap.put(i, 0); } for (ClimbingRoute route : ClimbingArea.getRoutes()) { String difficulty = route.getUIAARank(); int routeDifficulty = Utils.trimUIAARank(difficulty); if (difficultyMap.containsKey(routeDifficulty)) { difficultyMap.put(routeDifficulty, difficultyMap.get(routeDifficulty) + 1); } } ArrayList<BarEntry> routeDifficulties = new ArrayList<BarEntry>(); String[] xVals = new String[difficultyMap.size()]; List<Integer> orderedList = new ArrayList<>(difficultyMap.keySet()); Collections.sort(orderedList); int indexCounter = 0; for (Integer difficulty : orderedList) { xVals[indexCounter] = difficulty + ""; // BarEntry entry = new BarEntry(difficultyMap.get(difficulty), indexCounter++ , difficulty // +""); BarEntry entry = new BarEntry(difficulty, difficultyMap.get(difficulty), indexCounter++); routeDifficulties.add(entry); } mChart.getXAxis().setLabelCount(xVals.length); BarDataSet set1 = new BarDataSet(routeDifficulties, "Schwierigkeiten"); // set1.setColor(getResources().getColor(R.color.primary_700)); int[] uiaaChartColors = new int[AppConstants.UIAA_CHART_COLORS.length]; for (int i = 0; i < uiaaChartColors.length; ++i) { uiaaChartColors[i] = getResources().getColor(AppConstants.UIAA_CHART_COLORS[i]); } set1.setColors(uiaaChartColors); ArrayList<IBarDataSet> dataSets = new ArrayList<>(); dataSets.add(set1); BarData data = new BarData(dataSets); data.setValueFormatter(new MyValueFormatter()); data.setValueTextSize(10f); mChart.setData(data); mChart.animateX(1000); mChart.animateY(1000); }
@Override public void HttpResponse(String response) { Date xPoint = new Date(); String yPoint = ""; try { JSONObject reader = new JSONObject(response); String xString = reader.getString("Results"); String[] test = xString.split(","); for (String s : test) { s = s.replace('{', ' '); s = s.replace('}', ' '); s = s.replace('"', ' '); String[] mark = s.split(":"); Integer intTest; if (s.substring(12, 13).equals("0")) { // Log.d("paiva1",s.substring(13, 14) ); intTest = Integer.parseInt(s.substring(13, 14)); } else { // Log.d("paiva2",s.substring(12, 14).replace(" ", "") ); intTest = Integer.parseInt(s.substring(12, 14).replace(" ", "")); } // String str = "22:00"; // SimpleDateFormat ft = new SimpleDateFormat ("HH:mm"); // xPoint = ft.parse(str); yPoint = mark[2]; BarEntry measure = new BarEntry(Float.parseFloat(yPoint), intTest); // Measurements.add(measure); } } catch (JSONException e) { e.printStackTrace(); } BarDataSet setComp1 = new BarDataSet(Measurements, "Sähkötolpat"); setComp1.setAxisDependency(YAxis.AxisDependency.LEFT); dataSets.add(setComp1); BarData data = new BarData(xVals, dataSets); chart.setData(data); chart.invalidate(); }
private ArrayList<BarDataSet> getDataSet() { ArrayList<BarDataSet> dataSets = null; ArrayList<BarEntry> valueSet1 = new ArrayList<BarEntry>(); BarEntry v1e1 = new BarEntry(110.000f, 0); // Jan valueSet1.add(v1e1); BarEntry v1e2 = new BarEntry(40.000f, 1); // Feb valueSet1.add(v1e2); BarEntry v1e3 = new BarEntry(60.000f, 2); // Mar valueSet1.add(v1e3); BarEntry v1e4 = new BarEntry(30.000f, 3); // Apr valueSet1.add(v1e4); BarEntry v1e5 = new BarEntry(90.000f, 4); // May valueSet1.add(v1e5); BarEntry v1e6 = new BarEntry(100.000f, 5); // Jun valueSet1.add(v1e6); ArrayList<BarEntry> valueSet2 = new ArrayList<BarEntry>(); BarEntry v2e1 = new BarEntry(150.000f, 0); // Jan valueSet2.add(v2e1); BarEntry v2e2 = new BarEntry(90.000f, 1); // Feb valueSet2.add(v2e2); BarEntry v2e3 = new BarEntry(120.000f, 2); // Mar valueSet2.add(v2e3); BarEntry v2e4 = new BarEntry(60.000f, 3); // Apr valueSet2.add(v2e4); BarEntry v2e5 = new BarEntry(20.000f, 4); // May valueSet2.add(v2e5); BarEntry v2e6 = new BarEntry(80.000f, 5); // Jun valueSet2.add(v2e6); BarDataSet barDataSet1 = new BarDataSet(valueSet1, "Brand 1"); barDataSet1.setColor(Color.rgb(0, 155, 0)); BarDataSet barDataSet2 = new BarDataSet(valueSet2, "Brand 2"); barDataSet2.setColors(ColorTemplate.COLORFUL_COLORS); dataSets = new ArrayList<BarDataSet>(); dataSets.add(barDataSet1); dataSets.add(barDataSet2); return dataSets; }
private ArrayList<IBarDataSet> getiBarDataSets( List<BarEntry> dataListExpense, List<BarEntry> dataListIncome) { BarDataSet dataSetIncome = new BarDataSet(dataListIncome, mContext.getString(R.string.income)); dataSetIncome.setColor(ContextCompat.getColor(mContext, R.color.colorPrimaryGreen)); dataSetIncome.setDrawValues(false); BarDataSet dataSetExpense = new BarDataSet(dataListExpense, mContext.getString(R.string.expense)); dataSetExpense.setColor(ContextCompat.getColor(mContext, R.color.colorRed)); dataSetExpense.setDrawValues(false); ArrayList<IBarDataSet> dataSetList = new ArrayList<>(); switch (mSelectionType) { case IncomeExpenseAllType.INCOME: dataSetList.add(dataSetIncome); break; case IncomeExpenseAllType.EXPENSE: dataSetList.add(dataSetExpense); break; case IncomeExpenseAllType.ALL: dataSetList.add(dataSetIncome); dataSetList.add(dataSetExpense); break; } return dataSetList; }
private void setData(List<Integer> valueList, String format) { mChart.setVisibility(View.VISIBLE); ArrayList<String> xVals = new ArrayList<String>(); ArrayList<BarEntry> yVals1 = new ArrayList<BarEntry>(); if (valueList != null) { for (int i = 0; i < valueList.size(); i++) { xVals.add(i + "s"); yVals1.add(new BarEntry(valueList.get(i), i)); } } String legend = getResources().getString(R.string.caption_receptin_rate); if (!format.equals("%")) legend = getResources().getString(R.string.caption_packet_count); BarDataSet set1 = new BarDataSet(yVals1, legend); set1.setBarSpacePercent(35f); set1.setColor(Color.parseColor("#0288D1")); ArrayList<IBarDataSet> dataSets = new ArrayList<IBarDataSet>(); dataSets.add(set1); BarData data = new BarData(xVals, dataSets); data.setValueTextSize(10f); data.setDrawValues(false); YAxisValueFormatter custom = new DataAxisFormatter(format); YAxis leftAxis = mChart.getAxisLeft(); YAxis rightAxis = mChart.getAxisRight(); leftAxis.setValueFormatter(custom); rightAxis.setValueFormatter(custom); mChart.setData(data); }
@Override public RectF getBarBounds(BarEntry e) { BarDataSet set = mData.getDataSetForEntry(e); if (set == null) return null; float barspace = set.getBarSpace(); float y = e.getVal(); float x = e.getXIndex(); float spaceHalf = barspace / 2f; float top = x - 0.5f + spaceHalf; float bottom = x + 0.5f - spaceHalf; float left = y >= 0 ? y : 0; float right = y <= 0 ? y : 0; RectF bounds = new RectF(left, top, right, bottom); getTransformer(set.getAxisDependency()).rectValueToPixel(bounds); return bounds; }
/** * Returns the bounding box of the specified Entry in the specified DataSet. Returns null if the * Entry could not be found in the charts data. * * @param e * @return */ public RectF getBarBounds(final BarEntry e) { final BarDataSet set = this.mData.getDataSetForEntry(e); if (set == null) return null; final float barspace = set.getBarSpace(); final float y = e.getVal(); final float x = e.getXIndex(); final float barWidth = 0.5f; final float spaceHalf = barspace / 2f; final float left = x - barWidth + spaceHalf; final float right = x + barWidth - spaceHalf; final float top = y >= 0 ? y : 0; final float bottom = y <= 0 ? y : 0; final RectF bounds = new RectF(left, top, right, bottom); this.getTransformer(set.getAxisDependency()).rectValueToPixel(bounds); return bounds; }
@Override public DataSet<BarEntry> copy() { List<BarEntry> yVals = new ArrayList<BarEntry>(); yVals.clear(); for (int i = 0; i < mValues.size(); i++) { yVals.add(mValues.get(i).copy()); } BarDataSet copied = new BarDataSet(yVals, getLabel()); copied.mColors = mColors; copied.mStackSize = mStackSize; copied.mBarShadowColor = mBarShadowColor; copied.mStackLabels = mStackLabels; copied.mHighLightColor = mHighLightColor; copied.mHighLightAlpha = mHighLightAlpha; return copied; }
public static BarData formatData(JSONArray input) { ArrayList<BarEntry> entries = new ArrayList<>(); labels = new ArrayList<>(); boolean reachedCountries = false; int countryCounter = -1; int barDataCounter = -1; worldAverage = 0; try { for (int i = 0; i < input.length(); i++) { JSONObject set = input.getJSONObject(i); String val = set.getString("value"); if (val.equals("null")) { val = "0"; } JSONObject country = set.getJSONObject("country"); String countryName = country.getString("value"); // link the country name to its id because of urlgenerator purposes String countryID = country.getString("id"); // starts adding to countries array, only after it reaches all the countries if (countryName.toLowerCase().equals(firstCountry.toLowerCase())) { reachedCountries = true; } if (reachedCountries) { if (!countryName.equals("null")) { // this is for the drawer ++countryCounter; Preferences.cacheInformation("countryarray_" + countryCounter, countryName); // bar data float gdp = Float.valueOf(val); barDataCounter++; entries.add(new BarEntry(gdp, countryCounter)); // for better readability if (countryName.length() > 15) { countryName = countryName.substring(0, 15); } Preferences.cacheInformation(countryName.toLowerCase(), countryID.toLowerCase()); labels.add(countryName); // for the average line worldAverage += gdp; } } if (i == input.length() - 1) { Preferences.putInt("countryarray", countryCounter + 1); worldAverage = worldAverage / barDataCounter; } } } catch (JSONException e) { e.printStackTrace(); } BarDataSet dataset = new BarDataSet(entries, "GDP per capita (current US$)"); dataset.setColor(Color.rgb(120, 235, 235)); BarData data = new BarData(labels, dataset); return data; }
private void setData(DataParse mData) { kLineDatas = mData.getKLineDatas(); // axisLeftBar.setAxisMaxValue(mData.getVolmax()); String unit = MyUtils.getVolUnit(mData.getVolmax()); int u = 1; if ("万手".equals(unit)) { u = 4; } else if ("亿手".equals(unit)) { u = 8; } axisLeftBar.setValueFormatter(new VolFormatter((int) Math.pow(10, u))); // axisRightBar.setAxisMaxValue(mData.getVolmax()); Log.e("@@@", mData.getVolmax() + "da"); ArrayList<String> xVals = new ArrayList<>(); ArrayList<BarEntry> barEntries = new ArrayList<>(); ArrayList<CandleEntry> candleEntries = new ArrayList<>(); ArrayList<Entry> line5Entries = new ArrayList<>(); ArrayList<Entry> line10Entries = new ArrayList<>(); ArrayList<Entry> line30Entries = new ArrayList<>(); for (int i = 0, j = 0; i < mData.getKLineDatas().size(); i++, j++) { xVals.add(mData.getKLineDatas().get(i).date + ""); barEntries.add(new BarEntry(mData.getKLineDatas().get(i).vol, i)); candleEntries.add( new CandleEntry( i, mData.getKLineDatas().get(i).high, mData.getKLineDatas().get(i).low, mData.getKLineDatas().get(i).open, mData.getKLineDatas().get(i).close)); if (i >= 4) { sum = 0; line5Entries.add(new Entry(getSum(i - 4, i) / 5, i)); } if (i >= 9) { sum = 0; line10Entries.add(new Entry(getSum(i - 9, i) / 10, i)); } if (i >= 29) { sum = 0; line30Entries.add(new Entry(getSum(i - 29, i) / 30, i)); } } barDataSet = new BarDataSet(barEntries, "成交量"); barDataSet.setBarSpacePercent(50); // bar空隙 barDataSet.setHighlightEnabled(true); barDataSet.setHighLightAlpha(255); barDataSet.setHighLightColor(Color.WHITE); barDataSet.setDrawValues(false); barDataSet.setColor(Color.RED); BarData barData = new BarData(xVals, barDataSet); barChart.setData(barData); final ViewPortHandler viewPortHandlerBar = barChart.getViewPortHandler(); viewPortHandlerBar.setMaximumScaleX(culcMaxscale(xVals.size())); Matrix touchmatrix = viewPortHandlerBar.getMatrixTouch(); final float xscale = 3; touchmatrix.postScale(xscale, 1f); CandleDataSet candleDataSet = new CandleDataSet(candleEntries, "KLine"); candleDataSet.setDrawHorizontalHighlightIndicator(false); candleDataSet.setHighlightEnabled(true); candleDataSet.setHighLightColor(Color.WHITE); candleDataSet.setValueTextSize(10f); candleDataSet.setDrawValues(false); candleDataSet.setColor(Color.RED); candleDataSet.setShadowWidth(1f); candleDataSet.setAxisDependency(YAxis.AxisDependency.LEFT); CandleData candleData = new CandleData(xVals, candleDataSet); ArrayList<ILineDataSet> sets = new ArrayList<>(); sets.add(setMaLine(5, xVals, line5Entries)); sets.add(setMaLine(10, xVals, line10Entries)); sets.add(setMaLine(30, xVals, line30Entries)); CombinedData combinedData = new CombinedData(xVals); LineData lineData = new LineData(xVals, sets); combinedData.setData(candleData); combinedData.setData(lineData); combinedchart.setData(combinedData); combinedchart.moveViewToX(mData.getKLineDatas().size() - 1); final ViewPortHandler viewPortHandlerCombin = combinedchart.getViewPortHandler(); viewPortHandlerCombin.setMaximumScaleX(culcMaxscale(xVals.size())); Matrix matrixCombin = viewPortHandlerCombin.getMatrixTouch(); final float xscaleCombin = 3; matrixCombin.postScale(xscaleCombin, 1f); combinedchart.moveViewToX(mData.getKLineDatas().size() - 1); barChart.moveViewToX(mData.getKLineDatas().size() - 1); setOffset(); /** * ************************************************************************************** * 此处解决方法来源于CombinedChartDemo,k线图y轴显示问题,图表滑动后才能对齐的bug,希望有人给出解决方法 (注:此bug现已修复,感谢和chenguang79一起研究) * ************************************************************************************** */ handler.sendEmptyMessageDelayed(0, 300); }
private void setData(int count, float range) { // only using first meter for now. // TODO: graph multiple meters? Meter meter = mMeters.get(0); List<MeterReading> readings = meter.getReadings(); ArrayList<Entry> averageEntries = new ArrayList<Entry>(); // build up X-axis labels; e.g., dates. // build up Y-axis with values; // skip first date as we can't determine consumption. ArrayList<String> xVals = new ArrayList<String>(); ArrayList<BarEntry> yVals1 = new ArrayList<BarEntry>(); float runningTotal = 0; float dailyAverage; for (int lv = 1; lv < count; lv++) { MeterReading prevReading = readings.get(lv - 1); MeterReading currReading = readings.get(lv); xVals.add(removeYearFromDate(currReading.getTimeStamp())); float val = (currReading.getConsumption() - prevReading.getConsumption()) * 10; yVals1.add(new BarEntry(val, lv - 1)); // calc & store daily average. runningTotal += val; dailyAverage = runningTotal / lv; averageEntries.add(new Entry(dailyAverage, lv - 1)); } // TODO: allow name to be updated. BarDataSet set1 = new BarDataSet(yVals1, "mine"); set1.setBarSpacePercent(35f); ArrayList<BarDataSet> dataSets = new ArrayList<BarDataSet>(); dataSets.add(set1); // bar chart data BarData barData = new BarData(xVals, dataSets); barData.setValueFormatter(new MyValueFormatter()); barData.setValueTextSize(10f); // line chart data LineData lineData = new LineData(); LineDataSet set = new LineDataSet(averageEntries, "average"); int lineColor = Color.rgb(251, 169, 165); set.setColor(lineColor); set.setLineWidth(1.5f); set.setDrawCircles(false); set.setFillColor(lineColor); set.setDrawCubic(true); set.setDrawValues(false); set.setAxisDependency(YAxis.AxisDependency.LEFT); lineData.addDataSet(set); CombinedData combinedData = new CombinedData(getDates(meter.getReadings())); combinedData.setData(barData); combinedData.setData(lineData); mChart.setData(combinedData); mChart.invalidate(); }
/** Get the selected data and show it. */ private void drawData() { // Get shopping list in the dates range Select selectSLInRange = Select.from(ShoppingList.class) .whereOr( Condition.prop("date").gt(minDate.getTime().getTime()), Condition.prop("date").eq(minDate.getTime().getTime())) .and(Condition.prop("date").lt(maxDate.getTime().getTime())); List<ShoppingList> shoppingLists = selectSLInRange.list(); // Show number of shopping lists retrieved Toast.makeText(getActivity(), shoppingLists.size() + " shopping lists", Toast.LENGTH_SHORT) .show(); // If there's one or more, draw the chart // Each year is painted in one color. All the shopping list of one month must be // merge to get the total spend money amount of that month if (shoppingLists.size() > 0) { String[] mMonths = new String[] { "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" }; Collections.sort(shoppingLists); Map<String, List<BarEntry>> entrysYear = new HashMap<>(); List<String> labels = new ArrayList<>(); // First item Date date = shoppingLists.get(0).getDate(); Calendar cal = getInstance(); cal.setTime(date); int year = cal.get(YEAR); int month = cal.get(MONTH); entrysYear.put(year + "", new ArrayList<BarEntry>()); labels.add(mMonths[month % 12]); float totalPrice = 0; int newYear; int newMonth; for (int i = 0; i < shoppingLists.size(); i++) { Date d = shoppingLists.get(i).getDate(); Calendar c = getInstance(); c.setTime(d); newYear = c.get(YEAR); newMonth = c.get(MONTH); if (newMonth == month && newYear == year) { totalPrice += shoppingLists.get(i).getTotalPrice(); } else { // If not same year -> add new one if (newYear != year) { entrysYear.put(newYear + "", new ArrayList<BarEntry>()); } // If not same month -> save previous month BarEntry be = new BarEntry(totalPrice, labels.size() - 1); entrysYear.get(year + "").add(be); // Add new month labels.add(mMonths[newMonth % 12]); totalPrice = shoppingLists.get(i).getTotalPrice(); } year = newYear; month = newMonth; } // Save last one BarEntry be = new BarEntry(totalPrice, labels.size() - 1); entrysYear.get(year + "").add(be); BarData data = new BarData(labels); int i = 0; for (String name : entrysYear.keySet()) { BarDataSet dataset = new BarDataSet(entrysYear.get(name), name); dataset.setColor(ColorTemplate.COLORFUL_COLORS[i % ColorTemplate.COLORFUL_COLORS.length]); dataset.setBarSpacePercent(35f); data.addDataSet(dataset); i++; } data.setValueTextSize(10f); chart1.setData(data); chart1.notifyDataSetChanged(); // let the chart know it's data changed chart1.invalidate(); // refresh chart1.animateXY(1000, 1000); } }
private void setChart(BarChart barChart, double[][] values, String[] labels) { int[] colors = new int[5]; colors[0] = Color.argb(255, 11, 55, 144); colors[1] = Color.argb(255, 48, 120, 254); colors[2] = Color.argb(255, 123, 179, 254); colors[3] = Color.argb(255, 230, 230, 230); colors[4] = Color.argb(0, 255, 255, 255); ArrayList<BarEntry> dataEntries = new ArrayList<BarEntry>(); for (int i = 0; i < values.length; ++i) { float[] fList = new float[values[i].length]; for (int j = 0; j < values[i].length; ++j) { fList[j] = (float) values[i][j]; } dataEntries.add(new BarEntry(fList, i)); } BarDataSet dataSet = new BarDataSet(dataEntries, ""); dataSet.setBarSpacePercent(2f); dataSet.setStackLabels(new String[] {"浅睡眠", "深睡眠", "活动"}); dataSet.setColors(new int[] {colors[0], colors[1], colors[2]}); dataSet.setDrawValues(false); ArrayList<BarDataSet> dataSets = new ArrayList<BarDataSet>(); dataSets.add(dataSet); BarData barData = new BarData(labels, dataSets); barChart.setData(barData); YAxis leftAxis = barChart.getAxisLeft(); leftAxis.setDrawGridLines(true); leftAxis.setDrawLabels(false); leftAxis.setGridColor(colors[3]); leftAxis.setDrawAxisLine(true); leftAxis.setAxisLineColor(colors[3]); leftAxis.setAxisLineWidth(0.5f); YAxis rightAxis = barChart.getAxisRight(); rightAxis.setEnabled(true); rightAxis.setDrawLabels(false); rightAxis.setDrawGridLines(false); rightAxis.setAxisLineColor(colors[3]); rightAxis.setAxisLineWidth(0.5f); XAxis xAxis = barChart.getXAxis(); xAxis.setPosition(XAxisPosition.BOTTOM); xAxis.setDrawLabels(false); xAxis.setDrawGridLines(true); xAxis.setGridColor(colors[3]); xAxis.setAxisLineWidth(0.5f); xAxis.setAxisLineColor(colors[3]); barChart.setBackgroundColor(colors[4]); barChart.setGridBackgroundColor(colors[4]); barChart.getLegend().setEnabled(false); barChart.setScaleEnabled(false); barChart.setDescription(""); barChart.animateXY(2000, 2000); barChart.notifyDataSetChanged(); }