MPAndroidChart is there a way to set different colors for different bars?

ぐ巨炮叔叔 提交于 2020-01-02 07:15:44

问题


I am using MPAndroidChart in my app and i was wondering if there is a way to set a diferent color for the first bar in a dynamically moving bar chart, like this:

The bars are added dynamically while the whole stack is being moved to the left as the data keeps coming, is there a way to set the color of the first bar to be a different color? thank you in advance.

EDIT and Solution: here is my code for adding a new entry to the chart, it occurs dynamically every 500 millis or so.

 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();
    }
}

Thanks to @Philipp Jahoda I got it to work, just add this piece of code in you addEntry method:

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:


Yes, there is, it's in the documentation.

Basically you can set a separate color for each bar in the chart. It's a little inconvenient at the moment because in your case you have to set each color to "red" and the last color to "green".

I'm working on improving that.



来源:https://stackoverflow.com/questions/29879943/mpandroidchart-is-there-a-way-to-set-different-colors-for-different-bars

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!