MPAndroidChart StackedBarChart 显示值但没有条形图

MPAndroidChart StackedBarChart showing values but no bars

我开始使用 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>

问题是条形图没有正确呈现。我可以看到值,但条形图未显示在图表中。有什么建议吗?

我不得不从这个开始 StackedBarActivity example and going down one bit at a time until I figured out what's causing the problem. It's the use of the long timestamp from entry.getDate() for the X axis values with or without the custom IAxisValueFormatter. It's a bug in the library reported 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");
    }
};

我找到了另一种解决方法,即使您同时获得了过去和未来日期的时间戳,该方法也能奏效(请参阅 A.A 答案中的评论了解完整故事)。该技巧类似于当您必须在 X-axis 中绘制具有不同值的多个数据集时可以使用的技巧(参见 )。与其将时间戳直接放入 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));
            }
});

另一个漂亮的解决方法。只需在 BarEntry 中使用 TimeUnit.MILLISECONDS.toDays 并在 formatter

中使用 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;
    }
};

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

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

barData.setBarWidth(0.6f * widthBetweenObservations);

所以上面的设置条的宽度等于观测值之间距离的 60%。