MPAndroidChart堆积条形图显示数值但没有条形

5

我正在开始使用MPAndroidChart库构建一个显示三个y值的StackedBarChart。以下是代码:

public class Plot
{
    final Context context;
    final BarData data;

    private int count;

    public StackedBarPlot(Context context)
    {
        this.context = context;
        data = setData();
    }

    protected BarData setData()
    {
        final List<BarEntry> entries = new ArrayList<>();
        for (DatabaseEntry entry : entryList)
        {
            final float total = (float) entry.getTotal();
            final float[] y = {100 * entry.getN1() / total,
                    100 * entry.getN2() / total, 100 * entry.getN3() / total};
            entries.add(new BarEntry(/*long*/entry.getDate(), y));
        }
        count = entries.size();


        final BarDataSet dataset = new BarDataSet(entries, null);
        dataset.setColors(new int[]{R.color.green, R.color.blue, R.color.red}, context);
        dataset.setStackLabels(labels);
        dataset.setDrawValues(true);
        dataset.setVisible(true);

        final BarData data = new BarData(dataset);
        data.setBarWidth(0.9f);
        return data;
    }

    public BarChart getChart(int id, View view)
    {
        final BarChart chart = (BarChart) view.findViewById(id);   

        chart.getAxisRight().setEnabled(false);
        chart.getAxisLeft().setEnabled(false);
        final Legend legend = chart.getLegend();
        legend.setDrawInside(true);
        legend.setVerticalAlignment(Legend.LegendVerticalAlignment.TOP);
        legend.setHorizontalAlignment(Legend.LegendHorizontalAlignment.CENTER);

        final XAxis xAxis = chart.getXAxis();
        xAxis.setValueFormatter(dateFormatter);
        xAxis.setPosition(XAxis.XAxisPosition.BOTTOM);
        xAxis.setDrawGridLines(false);
        xAxis.setLabelCount(count);

        chart.getDescription().setEnabled(false);
        chart.setData(data);
        chart.setFitBars(true);
        chart.invalidate();
        return chart;
    }

    private final IAxisValueFormatter dateFormatter = new IAxisValueFormatter()
    {
        @Override
        public String getFormattedValue(float value, AxisBase axis)
        {
            return new DateTime((long) value).toString(context.getString("E, MMM d"));
        }
    };
}

然后在我的Fragment中,我调用:
public class MyFragment extends Fragment
{
    private Plot plot;

    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        plot = new Plot(getActivity());
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup parent, Bundle savedInstanceState)
    {
        final View view = inflater.inflate(R.layout.fragment, parent, false);
        plot.getChart(R.id.chart, view);
        return view;
    }
}

在MainActivity.java中

getFragmentManager().beginTransaction().replace(R.id.content, fragment).commit();

main_activity.xml

 <android.support.v4.widget.DrawerLayout
    android:id="@+id/drawer_layout"
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <android.support.design.widget.CoordinatorLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <android.support.design.widget.AppBarLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:theme="@style/AppTheme.AppBarOverlay">

            <android.support.v7.widget.Toolbar
                android:id="@+id/toolbar"
                android:layout_width="match_parent"
                android:layout_height="?attr/actionBarSize"
                android:background="?attr/colorPrimary"
                app:popupTheme="@style/AppTheme.PopupOverlay"/>

        </android.support.design.widget.AppBarLayout>

        <FrameLayout
            android:id="@+id/content"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            app:layout_behavior="@string/appbar_scrolling_view_behavior"/>
    </android.support.design.widget.CoordinatorLayout>

    <android.support.design.widget.NavigationView
        android:id="@+id/navigation"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:layout_gravity="start"
        android:fitsSystemWindows="true"
        app:headerLayout="@layout/drawer_header"
        app:menu="@menu/navigation"/>

</android.support.v4.widget.DrawerLayout>

fragment.xml

<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="16dp">

    <com.github.mikephil.charting.charts.BarChart
        android:id="@+id/chart"
        android:layout_width="match_parent"
        android:layout_height="match_parent"/>
</RelativeLayout>

问题在于条形图没有正确地渲染。我能看到数值,但是条形图没有显示在图表中。有什么建议吗?

我将代码复制粘贴到我的IDE中尝试进行调试,但存在一些未解决的依赖关系,这使得查看变得困难,并且缺乏有关如何使用图表的信息。请创建一个[MCVE],以便人们可以直接使用而不必加载您的项目。然而,我怀疑这是您设置图表容器XML的问题。 - David Rawson
@DavidRawson 已添加布局文件和完整的片段代码。 - A.A.
感谢您的更新 - 我认为当您将图表放在带有导航抽屉的活动中时,这可能是库中的一个错误。我需要进一步查看以确认。 - David Rawson
4个回答

11

这并不是库中的错误,就像之前的一些帖子所建议的那样。可能你只是像我第一次那样误解了每个条形图的宽度是如何确定的。

我在我的条形图x轴上使用了一个长的毫秒时间戳。我意识到,默认情况下MPAndroidChart将柱状图的宽度设置为0.85f。想想这意味着什么。我的第一个时间戳是1473421800000f,下一个是1473508200000f:两者之间相差86400000f!当每对观测值之间有86400000f时,我怎么能期望看到一个宽度为0.85f的条形图?要解决这个问题,您需要执行以下操作:

barData.setBarWidth(0.6f * widthBetweenObservations);

因此,上述设置将一个条形的宽度设置为等于观测值之间距离的60%。


2
这应该是被接受的答案,因为它解释了潜在的问题。 - leonardkraemer

1
我需要从 StackedBarActivity 示例开始,一点一点地找出问题所在。无论是否使用自定义的IAxisValueFormatter,都是由于使用了来自entry.getDate()的长时间戳作为X轴值而导致的问题。这是库中报告的一个错误here
以下是我最终采用的解决方法,获取自时间戳以来的持续时间(以天为单位):
long diff = new Duration(entry.getDate(), DateTime.now().getMillis()).getStandardDays();
entries.add(new BarEntry(diff, y));

然后在我的自定义IAxisValueFormatter中:

private final IAxisValueFormatter dateFormatter = new IAxisValueFormatter()
{
    @Override
    public String getFormattedValue(float value, AxisBase axis)
    {
        return LocalDate.now().minusDays((int) value).toString("EEE");
    }
};

1
非常感谢您提供的这个有用的答案。还有一些类似的问题! - David Rawson
如果你的时间戳包括过去和未来的日期,那么这个方法就不起作用了,因为该库只接受按其x位置排序的DataSet中添加的条目。你应该在计算出日期和DateTime.now()之间的持续时间后对条目进行排序,但这样会破坏你的数据。 - Keridano
@Keridano 对于你所描述的情况,它仍然可以工作。diff 的值可以是正数或负数,然后在格式化程序中,minusDays() 将在减去/添加差异后给出正确的日期。 - A.A.
问题出现在被调用的格式化程序之前。在库流程内,当尝试计算chart.setData()调用后的x.max和x.min时,应用程序会崩溃,因为数据未排序。 - Keridano
是的,我尝试了几种方法(我还用远未来和远过去的日期替换了参考日期而不是DateTime.now()),但每种情况下都出现了NegativeArraySizeException异常。我在MPAndroidChart问题列表中搜索并找到了这个链接:https://github.com/PhilJay/MPAndroidChart/issues/2074。 - Keridano
显示剩余3条评论

1
我找到了另一种解决方法,即使你有过去和未来日期的时间戳在一起(请参见A.A答案中的评论以获取完整故事),也可以使用该方法。这个技巧类似于当你必须在X轴上绘制多个具有不同值的数据集时可以使用的技巧(请参见https://stackoverflow.com/a/28549480/5098038)。不要直接将时间戳放入BarEntries x值中,而是创建一个包含时间戳的ArrayList,并将索引放入BarEntries中。然后,在格式化程序中,使用数据集中包含的值(索引)来获取Arraylist中包含的时间戳。

从原始时间戳值创建数组:

Long[] xTimestamps = { t1, t2, t3 };
List<Long> xArray  = new ArrayList<>(Arrays.asList(xTimestamps));

将索引添加到BarEntries中:

entries.add(new BarEntry(xArray.indexOf(t1), y));

使用格式化程序检索数据:
private static final SimpleDateFormat CHART_SDF = new SimpleDateFormat("dd/MM/yyyy", getApplicationContext().getResources().getConfiguration().locale);
private final IAxisValueFormatter dateFormatter = new IAxisValueFormatter() {
            @Override
            public String getFormattedValue(float value, AxisBase axis) {
                Long timestamp = xArray.get((int)value);
                return Chart_SDF.format(new Date(timestamp));
            }
});

1

还有一个漂亮的解决办法。只需在BarEntry中使用TimeUnit.MILLISECONDS.toDays,在格式化程序中使用TimeUnit.DAYS.toMillis。

Long dateInMills = someDateObject.getTime();
entries.add(new BarEntry(TimeUnit.MILLISECONDS.toDays(dateInMills), y));

然后在我的自定义IAxisValueFormatter中:

private final IAxisValueFormatter dateFormatter = new IAxisValueFormatter()
{
    @Override
    public String getFormattedValue(float value, AxisBase axis)
    {
            Float fVal = value;
            long mills = TimeUnit.DAYS.toMillis(fVal.longValue());
            ....
            //here convert mills to date and string
            ....
            return convertedString;
    }
};

请注意,时间将四舍五入,如果您的时间不是格林威治标准时间,时间将向前或向后移动一天... - Dmitry

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