我开始使用MPAndroidChart
库来构建一个StackedBarChart
显示三个y值.这是代码:
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 Listentries = 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
fragment.xml之
问题是条形图无法正确渲染.我可以看到值,但条形图没有显示.有什么建议?
这不像一些以前的帖子所建议的那样在库中出错.可能你只是误解了每个条的宽度是如何确定的,就像我最初做的那样.
我在条形图上为我的x轴使用了一个长的毫秒时间戳.我意识到默认情况下MPAndroidChart将条形宽度设置为0.85f.想想这意味着什么.我的第一个时间戳是1473421800000f,下一个是1473508200000f:相差86400000f!现在,当每对观测值之间有86400000f时,我怎么能看到一个0.85f宽的条形?要解决此问题,您需要执行以下操作:
barData.setBarWidth(0.6f * widthBetweenObservations);
因此,上面将条形的宽度设置为等于观察之间距离的60%.