MPAndroidChart的使用:水平柱状图
程序员文章站
2022-06-30 14:14:23
...
效果图如下:
水平柱状图与垂直柱状图的代码非常相似,将垂直柱状图中的x轴理解为水平柱状图中的y轴,将垂直柱状图中的y轴理解为水平柱状图的x轴就可以了。
垂直柱状图的文章如下:
代码如下:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="50dp">
<com.github.mikephil.charting.charts.HorizontalBarChart
android:id="@+id/horizontal_bar_chart"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
java代码如下:
public class HorizontalBarChartActivity extends AppCompatActivity {
private HorizontalBarChart barChart;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// 去除状态栏
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_horizontal_bar);
initBarChart();
}
private void initBarChart() {
barChart = findViewById(R.id.horizontal_bar_chart);
barChart.getDescription().setEnabled(false); // 不显示描述
barChart.getLegend().setEnabled(false); // 不显示图例
barChart.setExtraOffsets(30, 30, 30, 30); // 设置饼图的偏移量,类似于内边距 ,设置视图窗口大小
setAxis(); // 设置坐标轴
setData(); // 设置数据
}
private void setData() {
List<BarEntry> entryList = new ArrayList<>();
entryList.add(new BarEntry(0, 60.51f));
entryList.add(new BarEntry(1, 26.28f));
entryList.add(new BarEntry(2, 13.20f));
BarDataSet barDataSet = new BarDataSet(entryList, "");
barDataSet.setColors(Color.GREEN, Color.BLUE, Color.RED);
barDataSet.setValueTextColor(Color.RED);
barDataSet.setValueTextSize(15f);
barDataSet.setValueFormatter(new IValueFormatter() {
@Override
public String getFormattedValue(float v, Entry entry, int i, ViewPortHandler viewPortHandler) {
return v + "%";
}
});
BarData barData = new BarData(barDataSet);
barData.setBarWidth(0.4f); // 设置柱子的宽度
barChart.setData(barData);
}
/**
* 因为此处的柱状图为水平柱状图,所以x轴变y轴,y轴变x轴
*/
private void setAxis() {
XAxis xAxis = barChart.getXAxis();
xAxis.setPosition(XAxis.XAxisPosition.BOTTOM);
xAxis.setDrawGridLines(false);
xAxis.setTextSize(15f);
xAxis.setLabelCount(3);
xAxis.setGranularity(1f); // 防止放大图后,标签错乱
final String label[] = {"西瓜", "蓝莓", "草莓"};
xAxis.setValueFormatter(new IAxisValueFormatter() {
@Override
public String getFormattedValue(float v, AxisBase axisBase) {
try {
return label[(int) v];
} catch (Exception e) {
return "";
}
}
});
YAxis yAxis_right = barChart.getAxisRight();
yAxis_right.setAxisMinimum(0f);
yAxis_right.setAxisMaximum(100f);
yAxis_right.setTextSize(15f);
yAxis_right.setValueFormatter(new IAxisValueFormatter() {
@Override
public String getFormattedValue(float v, AxisBase axisBase) {
return v + "0%";
}
});
// 不显示最顶部的轴
YAxis yAxis_left = barChart.getAxisLeft();
yAxis_left.setAxisMinimum(0f);
yAxis_left.setAxisMaximum(100f);
yAxis_left.setEnabled(false);
}
}
上一篇: 5月份值得一看的 Java 技术干货!