需求:绘制12个月份的温度柱形
效果图:
单柱形效果图示例代码:
public class OneBarChartActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_one_bar_chart);
BarChart oneBarChart = findViewById(R.id.oneBarChart);
/**
* 需求:绘制12个月份的温度柱形
*/
List<Float> temperatures = Arrays.asList(20f, 24f,30f,40f,50f,60f,40f,20f,80f,40f,20f,80f);
final List<String> xList = Arrays.asList("一月", "二月","三月","四月","五月", "六月","七月","八月","九月", "十月","十一月","十二月");
//设置曲线整体的配置
oneBarChart.setNoDataText("暂无数据");
//设置绘制动画
oneBarChart.animateXY(1000, 1000);
//隐藏说明
oneBarChart.getDescription().setEnabled(false);
//设置X轴
XAxis xAxis = oneBarChart.getXAxis();
//xAxis.setAxisMinimum(0f); //不要用设置,否则可能柱形显示不全
xAxis.setLabelCount(12);
xAxis.setPosition(XAxis.XAxisPosition.BOTTOM);
//设置要不要X轴的网格,就是网格的竖线
xAxis.setDrawGridLines(false);
//不设置,否则getFormattedValue中的value就不是0,1,2,3,4
//xAxis.setCenterAxisLabels(true);
xAxis.setValueFormatter(new IAxisValueFormatter() {
@Override
public String getFormattedValue(float value, AxisBase axis) {
return xList.get((int) value);
}
});
//设置Y轴
YAxis rightYAxis = oneBarChart.getAxisRight();
//隐藏右边Y轴
rightYAxis.setEnabled(false);
YAxis leftYAxis = oneBarChart.getAxisLeft();
//leftYAxis.setAxisMinimum(0f); //不要用设置,否则可能柱形显示不全
//设置网格为虚线
leftYAxis.enableGridDashedLine(10f, 10f, 0f);
//设置数据
List<BarEntry> entries = new ArrayList<>();
for (int i = 0; i < 12; i++) {
entries.add(new BarEntry(i, temperatures.get(i)));
}
BarDataSet barDataSet = new BarDataSet(entries, "温度示例");
//设置柱形的颜色
barDataSet.setColor(Color.parseColor("#0000ff"));
BarData data = new BarData(barDataSet);
data.setBarWidth(0.3f);
oneBarChart.setData(data);
}
}
有问题加我QQ:893151960 或者请加群:142739277
网友评论