MPAndroidChart有没有办法为不同的柱状图设置不同的颜色?

5
我在我的应用中使用了MPAndroidChart,想知道是否有办法在动态移动的柱状图中为第一根柱子设置不同的颜色,就像这样: enter image description here 当数据不断增加时,整个堆栈向左移动时动态添加柱子,是否有办法将第一根柱子的颜色设置为不同的颜色? 提前感谢您。
编辑和解决方案: 下面是我向图表添加新条目的代码,每隔大约500毫秒就会发生一次动态更新。
 private void addBarEntry(float value) {


    BarData data = mDownloadChart.getData();

    if(data != null) {

        BarDataSet set = data.getDataSetByIndex(0);
        // set.addEntry(...); // can be called as well

        if (set == null) {
            set = createBarSet();
            data.addDataSet(set);
        }

        // add a new x-value first
        data.addXValue(set.getEntryCount() + "");

        // choose a random dataSet
        //int randomDataSetIndex = (int) (Math.random() * data.getDataSetCount());

        data.addEntry(new BarEntry(value, set.getEntryCount()), 0);

        // let the chart know it's data has changed
        mDownloadChart.notifyDataSetChanged();

        SLog.d(TAG, "download value: "+value);

        mDownloadChart.setVisibleXRange(10);
        mDownloadChart.moveViewToX(mDownloadChart.getHighestVisibleXIndex()-5);

        // redraw the chart
        mDownloadChart.invalidate();
    }
}

感谢@Philipp Jahoda,我已将其成功运行,请在addEntry方法中添加以下代码:
int[] colors = new int[set.getEntryCount()];
            for (int i = 0; i<colors.length; i++){
                colors[i]=Color.parseColor("your-hex-color-for-all-entries");
            }
            colors[colors.length-1] = Color.parseColor("your-hex-color-for-last-entry");

            set.setColors(colors);
1个回答

9

有的,它在文档中。

基本上你可以为图表中的每个条形设置单独的颜色。目前有点不方便,因为在你的情况下,你必须将每种颜色设置为“红色”,并将最后一种颜色设置为“绿色”。

我正在努力改进这个问题。


非常感谢!我已经编辑了我的问题并展示了解决方案。 - Ziv Kesten
1
@Philipp Jahoda for (int i = 0; i < barData.getDataSetCount(); i++) { BarDataSet barDataSet = barData.getDataSetByIndex(i); //dataset是BarEntry的数组 for (int j = 0; j < barDataSet.getEntryCount(); j++) { BarEntry barEntry = barDataSet.getEntryForXIndex(j); if(postData.getData().get(j).getPossiblity().equals("High")){ barDataSet.setColor(Color.parseColor("#29C391")); }else{ barDataSet.setColor(Color.RED); } } } - Karthikeyan Ve
1
@Phillipp Jahoda,您能否更详细地解释一下如何在MPAndroidChart中为单个条形设置单独的颜色? - Karthikeyan Ve

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接