【问题标题】:MPAndroidChart StackedBarChart showing values but no barsMPAndroidChart StackedBarChart 显示值但没有条形图
【发布时间】:2017-01-13 01:25:54
【问题描述】:

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

ma​​in_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 中以尝试调试它,但有一些未解决的依赖关系使其难以查看,并且缺乏有关您如何使用图表的信息。请创建一个minimal reproducible example,人们可以直接使用它而无需加载您的项目。但是,我怀疑这是您如何为图表容器设置 XML 的问题。
  • @DavidRawson 添加了布局文件和完整的片段代码
  • 感谢更新 - 我认为当您将图表放在带有导航抽屉的活动中时,这可能是库中的错误。我将不得不进一步确认

标签: android mpandroidchart


【解决方案1】:

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

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

barData.setBarWidth(0.6f * widthBetweenObservations);

因此,上面将条形的宽度设置为等于观察之间距离的 60%。

【讨论】:

  • 这应该是公认的答案,因为它解释了根本问题。
【解决方案2】:

我必须从这个StackedBarActivity example 开始,一次一点地往下走,直到我找出导致问题的原因。它使用来自entry.getDate() 的长时间戳来表示X 轴值,无论是否使用自定义IAxisValueFormatter。这是库中报告的一个错误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");
    }
};

【讨论】:

  • 非常感谢这个有用的答案。还有其他类似的问题!
  • 如果您同时拥有过去和未来日期的时间戳,这将不起作用,因为该库仅接受添加到按 x 位置排序的 DataSet 的条目。您应该在计算日期和 DateTime.now() 之间的 Duration 之后对条目进行排序,但是这样您的数据就会混乱
  • @Keridano 它仍然适用于您描述的情况。 diff 的值可以是正数也可以是负数,然后在格式化程序中,minusDays() 将在减去/加上差异后给出正确的日期。
  • 问题出在调用它的格式化程序之前。在您调用 chart.setData() 后,当它尝试计算 x.max 和 x.min 时,在库流程内部,应用程序将崩溃,因为数据未排序。
  • @Keridano 数据仍在排序中。它只有负值和正值。在确定它不起作用之前,您是否实际测试过该解决方案?
【解决方案3】:

我找到了另一种解决方法,即使您同时拥有过去和未来日期的时间戳,它仍然有效(完整故事请参阅 A.A 答案中的 cmets)。该技巧类似于您必须在 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));
            }
});

【讨论】:

    【解决方案4】:

    一个更漂亮的解决方法。只需在 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;
        }
    };
    

    【讨论】:

    • 小心。小时将四舍五入,如果您的时间不是格林威治标准时间,则时间将移动一天...
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-11-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多