【问题标题】:Android Combined bar and line graph MPAndroidChartAndroid 组合条线图 MPAndroidChart
【发布时间】:2017-01-10 10:37:26
【问题描述】:

我使用MpAndroidChart 绘制图表。我想将条形图和折线图结合在一起。我指的是 MpAndroidChart 示例的CombinedBarChart Activity。我无法删除堆栈栏。如何删除它?

下面是条形图数据:

ArrayList<BarEntry> entries1 = new ArrayList<BarEntry>();
    ArrayList<BarEntry> entries2 = new ArrayList<BarEntry>();

    for (int index = 0; index < itemcount; index++) {
        entries1.add(new BarEntry(0, getRandom(25, 25)));

        // stacked
        entries2.add(new BarEntry(0, new float[]{getRandom(13, 12), getRandom(13, 12)}));
    }

    BarDataSet set1 = new BarDataSet(entries1, "Bar 1");
    set1.setColor(Color.rgb(60, 220, 78));
    set1.setValueTextColor(Color.rgb(60, 220, 78));
    set1.setValueTextSize(10f);
    set1.setAxisDependency(YAxis.AxisDependency.LEFT);

    BarDataSet set2 = new BarDataSet(entries2, "");
    set2.setStackLabels(new String[]{"Stack 1", "Stack 2"});
    set2.setColors(new int[]{Color.rgb(61, 165, 255), Color.rgb(23, 197, 255)});
    set2.setValueTextColor(Color.rgb(61, 165, 255));
    set2.setValueTextSize(10f);
    set2.setAxisDependency(YAxis.AxisDependency.LEFT);

    float groupSpace = 0.06f;
    float barSpace = 0.02f; // x2 dataset
    float barWidth = 0.45f; // x2 dataset
    // (0.45 + 0.02) * 2 + 0.06 = 1.00 -> interval per "group"

    BarData d = new BarData(set1);
    d.setBarWidth(barWidth);

    // make this BarData object grouped
    d.groupBars(0, groupSpace, barSpace); // start at x = 0

如果我删除堆栈,我只会得到一个条。

【问题讨论】:

  • 如果你想把条和线结合在一起,你为什么只使用BarEntry作为数据集?你不应该也使用LineData 来获取 Line 表示吗?
  • 我也在使用它。我得到了正确的。但我没有得到条形图。

标签: android mpandroidchart


【解决方案1】:

问题在于您创建数据的位置,您始终设置条目的第一个元素,因此只会为“Bar 1”数据生成一列。添加数据时需要增加 x 索引。

  for (int index = 0; index < itemcount; index++) {
        entries1.add(new BarEntry(index, getRandom(25, 25)));
    }

另请注意,我不确定您的 getRandom 实际在做什么,但它看起来像是在产生 25 和 25 之间的随机值。我不确定这是否是意图。

【讨论】:

    【解决方案2】:

    你能试试这个吗?

    public class BarChartActivity extends DemoBase implements OnSeekBarChangeListener,
        OnChartValueSelectedListener {
    
    protected CombinedChart mChart;
    private SeekBar mSeekBarX, mSeekBarY;
    private TextView tvX, tvY;
    private int[] COLOR = {
            ColorTemplate.rgb("#F8F8F8"), ColorTemplate.rgb("#FFFFFF")
    };
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);
        setContentView(R.layout.activity_barchart);
    
        tvX = (TextView) findViewById(R.id.tvXMax);
        tvY = (TextView) findViewById(R.id.tvYMax);
    
        mSeekBarX = (SeekBar) findViewById(R.id.seekBar1);
        mSeekBarY = (SeekBar) findViewById(R.id.seekBar2);
    
        mChart = (CombinedChart) findViewById(R.id.chart1);
        mChart.setOnChartValueSelectedListener(this);
    
        mChart.setDrawBarShadow(false);
        mChart.setDrawValueAboveBar(true);
    
        mChart.setDescription("");
    
        // if more than 60 entries are displayed in the chart, no values will be
        // drawn
        mChart.setMaxVisibleValueCount(60);
    
        // scaling can now only be done on x- and y-axis separately
        mChart.setPinchZoom(false);
    
        mChart.setDrawGridBackground(false);
        // mChart.setDrawYLabels(false);
    
        IAxisValueFormatter xAxisFormatter = new DayAxisValueFormatter(mChart);
    
        XAxis xAxis = mChart.getXAxis();
        xAxis.setPosition(XAxisPosition.BOTTOM_INSIDE);
        xAxis.setTypeface(mTfLight);
        xAxis.setDrawGridLines(false);
        xAxis.setGranularity(1f); // only intervals of 1 day
        xAxis.setLabelCount(7);
        xAxis.setValueFormatter(xAxisFormatter);
    
        IAxisValueFormatter custom = new MyAxisValueFormatter();
    
        YAxis leftAxis = mChart.getAxisLeft();
        leftAxis.setTypeface(mTfLight);
        leftAxis.setLabelCount(8, false);
        leftAxis.setValueFormatter(custom);
        leftAxis.setPosition(YAxisLabelPosition.OUTSIDE_CHART);
        leftAxis.setSpaceTop(15f);
        leftAxis.setAxisMinimum(0f); // this replaces setStartAtZero(true)
    
        YAxis rightAxis = mChart.getAxisRight();
        rightAxis.setDrawGridLines(false);
        rightAxis.setTypeface(mTfLight);
        rightAxis.setLabelCount(8, false);
        rightAxis.setValueFormatter(custom);
        rightAxis.setSpaceTop(15f);
        rightAxis.setAxisMinimum(0f); // this replaces setStartAtZero(true)
    
        Legend l = mChart.getLegend();
        l.setPosition(LegendPosition.BELOW_CHART_LEFT);
        l.setForm(LegendForm.SQUARE);
        l.setFormSize(9f);
        l.setTextSize(11f);
        l.setXEntrySpace(4f);
        // l.setExtra(ColorTemplate.VORDIPLOM_COLORS, new String[] { "abc",
        // "def", "ghj", "ikl", "mno" });
        // l.setCustom(ColorTemplate.VORDIPLOM_COLORS, new String[] { "abc",
        // "def", "ghj", "ikl", "mno" });
    
        XYMarkerView mv = new XYMarkerView(this, xAxisFormatter);
        mv.setChartView(mChart); // For bounds control
        mChart.setMarker(mv); // Set the marker to the chart
    
        setData(20, 50);
    
        // setting data
        mSeekBarY.setProgress(50);
        mSeekBarX.setProgress(12);
    
        mSeekBarY.setOnSeekBarChangeListener(this);
        mSeekBarX.setOnSeekBarChangeListener(this);
    
        // mChart.setDrawLegend(false);
    }
    
    
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.bar, menu);
        return true;
    }
    
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
    
        switch (item.getItemId()) {
            case R.id.actionToggleValues: {
                for (IDataSet set : mChart.getData().getDataSets())
                    set.setDrawValues(!set.isDrawValuesEnabled());
    
                mChart.invalidate();
                break;
            }
            case R.id.actionToggleHighlight: {
                if (mChart.getData() != null) {
                    mChart.getData().setHighlightEnabled(!mChart.getData().isHighlightEnabled());
                    mChart.invalidate();
                }
                break;
            }
            case R.id.actionTogglePinch: {
                if (mChart.isPinchZoomEnabled())
                    mChart.setPinchZoom(false);
                else
                    mChart.setPinchZoom(true);
    
                mChart.invalidate();
                break;
            }
            case R.id.actionToggleAutoScaleMinMax: {
                mChart.setAutoScaleMinMaxEnabled(!mChart.isAutoScaleMinMaxEnabled());
                mChart.notifyDataSetChanged();
                break;
            }
            case R.id.actionToggleBarBorders: {
                /*for (IBarDataSet set : mChart.getData().getDataSets())
                    ((BarDataSet) set).setBarBorderWidth(set.getBarBorderWidth() == 1.f ? 0.f : 1.f);*/
    
                mChart.invalidate();
                break;
            }
            case R.id.animateX: {
                mChart.animateX(3000);
                break;
            }
            case R.id.animateY: {
                mChart.animateY(3000);
                break;
            }
            case R.id.animateXY: {
    
                mChart.animateXY(3000, 3000);
                break;
            }
            case R.id.actionSave: {
                if (mChart.saveToGallery("title" + System.currentTimeMillis(), 50)) {
                    Toast.makeText(getApplicationContext(), "Saving SUCCESSFUL!",
                            Toast.LENGTH_SHORT).show();
                } else
                    Toast.makeText(getApplicationContext(), "Saving FAILED!", Toast.LENGTH_SHORT)
                            .show();
                break;
            }
        }
        return true;
    }
    
    @Override
    public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
    
        tvX.setText("" + (mSeekBarX.getProgress() + 2));
        tvY.setText("" + (mSeekBarY.getProgress()));
    
        setData(mSeekBarX.getProgress() + 1, mSeekBarY.getProgress());
        mChart.invalidate();
    }
    
    @Override
    public void onStartTrackingTouch(SeekBar seekBar) {
        // TODO Auto-generated method stub
    }
    
    @Override
    public void onStopTrackingTouch(SeekBar seekBar) {
        // TODO Auto-generated method stub
    }
    
    private void setData(int count, float range) {
    
        float start = 0f;
    
        mChart.getXAxis().setAxisMinimum(start);
        mChart.getXAxis().setAxisMaximum(start + count + 2);
    
        ArrayList<BarEntry> yVals1 = new ArrayList<BarEntry>();
        ArrayList<Entry> entries = new ArrayList<Entry>();
        int size = (int)(start + count + 1);
    
        int[] COLOR_LINE = new int[size];
        for (int i = (int) start; i < 10; i++) {
            yVals1.add(new BarEntry(i + 1f, 300));
        }
    
        for (int i = (int) start; i < 5; i++) {
            float mult = (range + 1);
            float val = getRandom(90, 50); //float val = (float) (Math.random() * mult);
    
    
    
    
            entries.add(new Entry(i + 1f, val));
            COLOR_LINE[i] = (val < 70 ? Color.RED : Color.rgb(115, 180, 236));
    
        }
    
    
        LineData d = new LineData();
    
        LineDataSet set = new LineDataSet(entries, "Line DataSet");
        set.setColors(COLOR_LINE);
        set.setLineWidth(1f);
        set.setCircleColor(Color.rgb(240, 238, 70));
        set.setCircleRadius(5f);
        set.setFillColor(Color.rgb(240, 238, 70));
        set.setMode(LineDataSet.Mode.LINEAR);
        set.setDrawValues(true);
        set.setValueTextSize(10f);
        set.setValueTextColor(Color.rgb(115, 180, 236));
    
        set.setAxisDependency(YAxis.AxisDependency.LEFT);
        d.addDataSet(set);
    
    
        BarDataSet set1;
    
        if (mChart.getData() != null &&
                mChart.getData().getDataSetCount() > 0) {
            set1 = (BarDataSet) mChart.getData().getDataSetByIndex(0);
            set1.setValues(yVals1);
            mChart.getData().notifyDataChanged();
            mChart.notifyDataSetChanged();
        } else {
            set1 = new BarDataSet(yVals1, "The year 2017");
            set1.setColors(COLOR);
    
            ArrayList<IBarDataSet> dataSets = new ArrayList<IBarDataSet>();
            dataSets.add(set1);
    
            BarData data = new BarData(dataSets);
            data.setValueTextSize(10f);
            data.setValueTypeface(mTfLight);
            data.setBarWidth(0.9f);
            data.setBarWidth(1f);
    
            //mChart.setData(data);
    
            CombinedData combinedData = new CombinedData();
    
            combinedData.setData(data);
            combinedData.setData(d);
            combinedData.setValueTypeface(mTfLight);
    
    
            mChart.setData(combinedData);
            mChart.setScaleMinima((float) (data.getXMax() + 0.25f)/10f, 1f);
            for (IDataSet set11 : mChart.getData().getDataSets()) {
                if (set11 instanceof BarDataSet)
                    set11.setDrawValues(!set11.isDrawValuesEnabled());
            }
    
            mChart.invalidate();
        }
    }
    
    protected RectF mOnValueSelectedRectF = new RectF();
    
    @SuppressLint("NewApi")
    @Override
    public void onValueSelected(Entry e, Highlight h) {
    
        if (e == null)
            return;
    
        RectF bounds = mOnValueSelectedRectF;
        //mChart.getBarBounds((BarEntry) e, bounds);
        MPPointF position = mChart.getPosition(e, AxisDependency.LEFT);
    
        Log.i("bounds", bounds.toString());
        Log.i("position", position.toString());
    
        Log.i("x-index",
                "low: " + mChart.getLowestVisibleX() + ", high: "
                        + mChart.getHighestVisibleX());
    
        MPPointF.recycleInstance(position);
    }
    
    @Override
    public void onNothingSelected() {
    }
    

    }

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多