I am using MPAndroidChart and I want to create a barchart. Actually this works fine. But the problem are the labels on the different bars. Somehow they just don't match. Only if I have exactly 3 bars, the labels are being displayed correctly. Here you can see a picture: enter image description here

以下是Java Android代码:

import android.graphics.Color;
import android.graphics.Typeface;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.fragment.app.Fragment;

import com.example.drinkserver.databinding.FragmentTestBinding;
import com.github.mikephil.charting.components.LimitLine;
import com.github.mikephil.charting.components.XAxis;
import com.github.mikephil.charting.components.YAxis;
import com.github.mikephil.charting.data.BarData;
import com.github.mikephil.charting.data.BarDataSet;
import com.github.mikephil.charting.data.BarEntry;
import com.github.mikephil.charting.formatter.IndexAxisValueFormatter;

import java.util.ArrayList;
import java.util.List;


public class FR_Test extends Fragment {


    public FR_Test() {
        // Required empty public constructor
    }



    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);


    }
    private FragmentTestBinding binding;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        binding = FragmentTestBinding.inflate(inflater, container, false);
        /*
        Create barcharts with MP Android Chart
         */

        //Add data points
        ArrayList<BarEntry> dataVals = new ArrayList<>();
        dataVals.add(new BarEntry(1, 3));
        //dataVals.add(new BarEntry(2, 4));
        //dataVals.add(new BarEntry(3, 5));
        //dataVals.add(new BarEntry(4, 3));


        // Create a BarDataSet with the data
        BarDataSet barDataSet = new BarDataSet(dataVals, "");
        barDataSet.setDrawValues(true); 
        barDataSet.setValueTextColor(Color.BLACK); 

        // Customize the appearance of the bars
        barDataSet.setColors(Color.rgb(0, 155, 0)); // Set bar color

        // Create BarData and add your BarDataSet to it
        BarData barData = new BarData(barDataSet);
        barData.setBarWidth(0.6f);

        // Get the XAxis
        XAxis xAxis = binding.barChartRatings.getXAxis();
        xAxis.setPosition(XAxis.XAxisPosition.BOTTOM);
        xAxis.setDrawAxisLine(true); 
        xAxis.setDrawGridLines(false); 
        xAxis.setTextSize(10f); 
        xAxis.setTypeface(Typeface.DEFAULT_BOLD); 
        
        // Add labels for the bars
        List<String> barLabels = new ArrayList<>();
        barLabels.add("");
        for (int i = 0; i < dataVals.size(); i++) {
            barLabels.add("Bar " + (i + 1));
        }

        // Convert the list to an array
        final String[] barLabelsA = barLabels.toArray(new String[0]);

        // Set the custom labels for the X-axis
        xAxis.setValueFormatter(new IndexAxisValueFormatter(barLabelsA));


        // Get the YAxis (left axis)
        YAxis leftYAxis = binding.barChartRatings.getAxisLeft();
        leftYAxis.setDrawLabels(true); 
        leftYAxis.setDrawGridLines(true); 
        leftYAxis.setAxisMinimum(0f); 
        leftYAxis.setAxisMaximum(5.5f); 
        leftYAxis.setGranularity(1f);
        // Set the number of labels without forcing them to be integers
        leftYAxis.setLabelCount(6, false); 
        leftYAxis.setTextSize(14f);

        // Create a LimitLine for the upper rim
        LimitLine upperRim = new LimitLine(5.5f, "");
        upperRim.setLineColor(Color.BLACK);
        upperRim.setLineWidth(1f);

        // Add the upper rim to the left YAxis
        leftYAxis.addLimitLine(upperRim);

        // Get the YAxis and hide it
        YAxis rightYAxis = binding.barChartRatings.getAxisRight();
        rightYAxis.setDrawLabels(false);
        rightYAxis.setDrawGridLines(false);

        // Add a continuous upper rim to the plot
        binding.barChartRatings.getAxisRight().setDrawTopYLabelEntry(true);
        binding.barChartRatings.getAxisLeft().setDrawTopYLabelEntry(true);

        // Remove the legend
        binding.barChartRatings.getLegend().setEnabled(false);

        // Hide the description label
        binding.barChartRatings.getDescription().setEnabled(false);

        // Set data for the bar chart
        binding.barChartRatings.setData(barData);


        // Invalidate the chart to refresh its appearance
        binding.barChartRatings.invalidate();


        return binding.getRoot();
    }
}

下面是相应的XML布局文件:

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 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:background="@color/colorGrey"
    android:layout_width="match_parent"
    android:layout_height="match_parent">


    <com.github.mikephil.charting.charts.BarChart
        android:id="@+id/barChartRatings"
        android:layout_width="220dp"
        android:layout_height="220dp"


        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />


</androidx.constraintlayout.widget.ConstraintLayout>

List<String> barLabels = new ArrayList<>();个人总是有正确数量的小节弦.因此,当只有一个数据点时,它有一个空字符串""(这样Bar标签不会显示在位置0)和"bar1".所以很奇怪,为什么"bar1"会重复3次.让这个问题更奇怪的是,当有不同数量的wine 吧时,行为会发生变化,尽管barLabels 的字符串数量总是正确的.你知道是什么导致了这个问题吗?

推荐答案

你有两个问题. 创建BarEntry对象时,必须从0而不是1初始化X值.此外,在向barLabels变量添加空格时犯了逻辑错误,可以按如下方式添加空格.

dataVals.add(new BarEntry(0, 3)); // Bar 1
dataVals.add(new BarEntry(1, 4)); // Bar 2
dataVals.add(new BarEntry(2, 5)); // Bar 3
dataVals.add(new BarEntry(3, 3)); // Bar 4
//add more bar if you want

// ...

       // Add labels for the bars (change your add space character method)
        List<String> barLabels = new ArrayList<>();
        for (int i = 0; i < dataVals.size(); i++) {
            //ADD SPACE HERE
            barLabels.add("Bar " + (i + 1));
        }

        // Convert the list to an array
        final String[] barLabelsA = barLabels.toArray(new String[0]);

// ...

要使标签完全按照条形居中,您可以在代码中添加以下方法:(您为yAxis添加了此方法,但没有为Xaxis添加此方法.)

xAxis.setGranularity(1f);

当我try 它的时候它起作用了,我希望它对你起作用.

barchart view

Java相关问答推荐

Maven Google Sheets版本问题

如何使用解析器组合子解析Java数组类型签名?

JPackaged应用程序启动MSI调试,然后启动System. exit()

多个Java线程和TreeMap.put()的非预期行为

有关手动创建的包的问题

扩展到弹出窗口宽度的JavaFX文本字段

暂停计时器

我可以在MacOS上使用什么Java函数来在适当的设备上以适当的音量播放适当的alert 声音?

使用Room Database删除Jetpack合成中的所有项目后,UI未重新合成

声明MessageChannel Bean的首选方式

虚拟线程应该很快消亡吗?

如何在Spring Boot中创建可以将值传递给配置的&Enable&Quot;注释?

插入中的JOOQ序列,设置为VS值

JavaFX标签中的奇怪字符

如何在字节数组中反转UTF-8编码?

为什么项目名称出现在我的GET请求中?

处理4.3问题:javax.xml.ind包不存在(&Q;).您可能在学习GitHub教程时遗漏了库.&Q

JavaFX:为什么我的ComboBox添加了一个不必要的单元格的一部分?

字符串的Gzip压缩在java11和java17中给出了不同的结果

spring 数据Elastic search 与 spring 启动数据Elastic search 之间的区别是什么?