我的X轴数值没有对齐。我应该修改哪个设置?
以下是我目前在代码中拥有的内容,但.setLabelsToSkip不起作用,因为我正在使用3.0.1版本。
XAxis xAxis = mChart.getXAxis();
xAxis.setTypeface(mTfLight);
xAxis.setGranularity(1f);
xAxis.setCenterAxisLabels(true);
xAxis.setDrawLabels(true);
xAxis.setGranularity(1f);
xAxis.setGranularityEnabled(true);
xAxis.setPosition(XAxis.XAxisPosition.BOTTOM);
xAxis.setTextColor(Color.WHITE);
xAxis.setTextSize(15);
这是我的LabelFormatter类:
import com.github.mikephil.charting.components.AxisBase;
import com.github.mikephil.charting.formatter.IAxisValueFormatter;
public class LabelFormatter implements IAxisValueFormatter {
private final String[] mLabels;
public LabelFormatter(String[] labels) {
mLabels = labels;
}
@Override
public String getFormattedValue(float value, AxisBase axis) {
return mLabels[(int) value];
}
}
这是我的主活动设置数据方法:
private void setData() {
ArrayList<BarEntry> entries = new ArrayList<>();
String labels[]=new String[5];
for (Cars c : values) {
if (c.getX()==1){
labels[0] = "Engine 1";
}
if (c.getX()==2){
labels[1] = "Engine 2";
}
if (c.getX()==3){
labels[2] = "Engine 3";
}
if (c.getX()==4){
labels[3] = "Engine 4";
}
if (c.getX()==5){
labels[4] = "Engine 5";
}
entries.add(new BarEntry((float) c.getX(), ((float) c.getY()),labels));
}
BarDataSet set1;
if (mChart.getData() != null && mChart.getData().getDataSetCount() > 0) {
set1 = (BarDataSet) mChart.getData().getDataSetByIndex(0);
set1.setValues(entries);
mChart.getXAxis().setValueFormatter(new IndexAxisValueFormatter(labels));
//set1.setValueFormatter(new LabelFormatter(labels));
//mChart.getXAxis().setValueFormatter(new BarValueFormatter(set1));
mChart.getData().notifyDataChanged();
mChart.notifyDataSetChanged();
} else {
set1 = new BarDataSet(entries, "Engine Types");
ArrayList<Integer> colors = new ArrayList<Integer>();
for (int c : ColorTemplate.VORDIPLOM_COLORS)
colors.add(c);
for (int c : ColorTemplate.JOYFUL_COLORS)
colors.add(c);
for (int c : ColorTemplate.COLORFUL_COLORS)
colors.add(c);
for (int c : ColorTemplate.LIBERTY_COLORS)
colors.add(c);
for (int c : ColorTemplate.PASTEL_COLORS)
colors.add(c);
colors.add(ColorTemplate.getHoloBlue());
set1.setColors(colors);
ArrayList<IBarDataSet> dataSets = new ArrayList<IBarDataSet>();
dataSets.add(set1);
mChart.getXAxis().setValueFormatter(new IndexAxisValueFormatter(labels));
//mChart.getXAxis().setValueFormatter(new LabelFormatter(labels));
//mChart.getXAxis().setValueFormatter(new BarValueFormatter(set1));
BarData data = new BarData(dataSets);
data.setValueTextSize(50f);
data.setValueTextColor(Color.WHITE);
data.setValueTypeface(mTfLight);
mChart.setData(data);
}
}
在我的主活动中,我这样使用它:
mChart.getXAxis().setValueFormatter(new IndexAxisValueFormatter(labels));
IndexValueFormatter
? - David RawsonIndexValueFormatter
还是LabelFormatter
?你的代码展示了两者,所以不太清楚。此外,不要使用(int) value
,因为它总是向下取整。请使用int index = Math.round(value);
。 - David Rawson