如何使用MPAndroidChart创建带有分组条形的BarChart?

时间:2016-02-06 11:09:51

标签: android graph mpandroidchart

如何使用MPAndroidChartBarChart比较两组数据。

它应该如下图所示: enter image description here

我编辑了一段代码,我从github的示例项目中获取。 如何将100f and 110f值放在一个Xaxis标签Whole Number

        Score score1 = new Score(100f, 0, "Whole Number");
        mRealm.copyToRealm(score1);
        Score score2 = new Score(110f, 0, "Whole Number");
        mRealm.copyToRealm(score2);

4 个答案:

答案 0 :(得分:18)

是的,这可以很容易地完成。

您需要的是BarChart多个BarDataSets,其中每一组(在您的情况下)代表一种性别(男性或女性)。

示例代码(不含realm.io)

    List<String> xValues = ...; // "Denmark", "Finland", ...

    XAxis xAxis = chart.getXAxis();
    xAxis.setValueFormatter(new MyValueFormatter(xValues));

    // create 2 datasets 
    BarDataSet set1 = new BarDataSet(valuesMen, "Men");
    set1.setColor(Color.BLUE);
    BarDataSet set2 = new BarDataSet(valuesWomen, "Women");
    set2.setColor(Color.RED);

    BarData data = new BarData(set1, set2);
    chart.setData(data);
    chart.groupBars(...); // available since release v3.0.0
    chart.invalidate(); // refresh

如果您需要进一步的帮助,维基上可以使用BarChart分组BarChart

如果您希望将#import <Foundation/Foundation.h> #import <MobileCoreServices/MobileCoreServices.h> #import <UIKit/UIKit.h> #import <Photos/Photos.h> #import "RCTBridgeModule.h" #import "RCTLog.h" @interface FileUpload : NSObject <RCTBridgeModule, NSURLSessionDataDelegate, NSURLSessionDelegate, NSURLSessionTaskDelegate> @end @implementation FileUpload RCT_EXPORT_MODULE(); RCT_EXPORT_METHOD(upload:(NSDictionary *)obj callback:(RCTResponseSenderBlock)callback) { NSString *uploadUrl = obj[@"uploadUrl"]; NSDictionary *headers = obj[@"headers"]; NSDictionary *fields = obj[@"fields"]; NSArray *files = obj[@"files"]; NSString *method = obj[@"method"]; if ([method isEqualToString:@"POST"] || [method isEqualToString:@"PUT"]) { } else { method = @"POST"; } NSURL *url = [NSURL URLWithString:uploadUrl]; NSMutableURLRequest *req = [NSMutableURLRequest requestWithURL:url]; [req setHTTPMethod:method]; // set headers NSString *formBoundaryString = [self generateBoundaryString]; NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@", formBoundaryString]; [req setValue:contentType forHTTPHeaderField:@"Content-Type"]; for (NSString *key in headers) { id val = [headers objectForKey:key]; if ([val respondsToSelector:@selector(stringValue)]) { val = [val stringValue]; } if (![val isKindOfClass:[NSString class]]) { continue; } [req setValue:val forHTTPHeaderField:key]; } NSData *formBoundaryData = [[NSString stringWithFormat:@"--%@\r\n", formBoundaryString] dataUsingEncoding:NSUTF8StringEncoding]; NSMutableData* reqBody = [NSMutableData data]; // add fields for (NSString *key in fields) { id val = [fields objectForKey:key]; if ([val respondsToSelector:@selector(stringValue)]) { val = [val stringValue]; } if (![val isKindOfClass:[NSString class]]) { continue; } [reqBody appendData:formBoundaryData]; [reqBody appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"%@\"\r\n\r\n", key] dataUsingEncoding:NSUTF8StringEncoding]]; [reqBody appendData:[val dataUsingEncoding:NSUTF8StringEncoding]]; [reqBody appendData:[@"\r\n" dataUsingEncoding:NSUTF8StringEncoding]]; } // add files for (NSDictionary *file in files) { NSString *name = file[@"name"]; NSString *filename = file[@"filename"]; NSString *filepath = file[@"filepath"]; NSString *filetype = file[@"filetype"]; NSData *fileData = nil; NSLog(@"filepath: %@", filepath); if ([filepath hasPrefix:@"assets-library:"]) { NSURL *assetUrl = [[NSURL alloc] initWithString:filepath]; __block NSData * tempData = nil; PHFetchResult *result = [PHAsset fetchAssetsWithALAssetURLs:@[assetUrl] options:nil]; PHAsset *asset = result.firstObject; if (asset) { PHCachingImageManager *imageManager = [[PHCachingImageManager alloc] init]; // Request an image for the asset from the PHCachingImageManager. [imageManager requestImageForAsset:asset targetSize:CGSizeMake(100.0f, 100.0f) contentMode:PHImageContentModeAspectFill options:nil resultHandler:^(UIImage *image, NSDictionary *info) { NSLog(@"IMAGE: %@", image); tempData = UIImagePNGRepresentation(image); }]; } fileData = tempData; } else if ([filepath hasPrefix:@"data:"] || [filepath hasPrefix:@"file:"]) { NSURL *fileUrl = [[NSURL alloc] initWithString:filepath]; fileData = [NSData dataWithContentsOfURL: fileUrl]; } else { fileData = [NSData dataWithContentsOfFile:filepath]; } [reqBody appendData:formBoundaryData]; [reqBody appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"%@\"; filename=\"%@\"\r\n", name.length ? name : filename, filename] dataUsingEncoding:NSUTF8StringEncoding]]; if (filetype) { [reqBody appendData:[[NSString stringWithFormat:@"Content-Type: %@\r\n", filetype] dataUsingEncoding:NSUTF8StringEncoding]]; } else { [reqBody appendData:[[NSString stringWithFormat:@"Content-Type: %@\r\n", [self mimeTypeForPath:filename]] dataUsingEncoding:NSUTF8StringEncoding]]; } [reqBody appendData:[[NSString stringWithFormat:@"Content-Length: %ld\r\n\r\n", (long)[fileData length]] dataUsingEncoding:NSUTF8StringEncoding]]; [reqBody appendData:fileData]; [reqBody appendData:[@"\r\n" dataUsingEncoding:NSUTF8StringEncoding]]; } // add end boundary NSData* end = [[NSString stringWithFormat:@"--%@--\r\n", formBoundaryString] dataUsingEncoding:NSUTF8StringEncoding]; [reqBody appendData:end]; // send request [req setHTTPBody:reqBody]; NSURLSessionConfiguration *sessionConfiguration = [NSURLSessionConfiguration defaultSessionConfiguration]; NSURLSession *session = [NSURLSession sessionWithConfiguration:sessionConfiguration delegate:(id)self delegateQueue:[NSOperationQueue mainQueue]]; NSURLSessionDataTask *task = [session dataTaskWithRequest:req completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) { NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *) response; NSLog(@"response status code: %ld", (long)[httpResponse statusCode]); callback(@[[NSNull null], [NSString stringWithFormat:@"response status code: %ld", (long)[httpResponse statusCode]]]); }]; [task resume]; } - (NSString *)generateBoundaryString { NSString *uuid = [[NSUUID UUID] UUIDString]; return [NSString stringWithFormat:@"----%@", uuid]; } - (NSString *)mimeTypeForPath:(NSString *)filepath { NSString *fileExtension = [filepath pathExtension]; NSString *UTI = (__bridge_transfer NSString *)UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension, (__bridge CFStringRef)fileExtension, NULL); NSString *contentType = (__bridge_transfer NSString *)UTTypeCopyPreferredTagWithClass((__bridge CFStringRef)UTI, kUTTagClassMIMEType); if (contentType) { return contentType; } return @"application/octet-stream"; } - (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveResponse:(NSURLResponse *)response completionHandler:(void (^)(NSURLSessionResponseDisposition disposition))completionHandler { completionHandler(NSURLSessionResponseAllow); NSLog(@"didReceiveResponse"); } - (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveData:(NSData *)data { NSLog(@"didReceiveData"); } @end 中的值“叠加”在一起,则需要创建堆叠条形图:detailed tutorial

答案 1 :(得分:17)

由于BarData构造函数已有更新,因此您需要使用以下代码:

        BarChart barChart = (BarChart) view.findViewById(R.id.chart);

        barChart.setDrawBarShadow(false);
        barChart.setDrawValueAboveBar(true);
        barChart.setDescription("");
        barChart.setMaxVisibleValueCount(50);
        barChart.setPinchZoom(false);
        barChart.setDrawGridBackground(false);

        XAxis xl = barChart.getXAxis();
        xl.setGranularity(1f);
        xl.setCenterAxisLabels(true);
        xl.setValueFormatter(new AxisValueFormatter() {
            @Override
            public String getFormattedValue(float value, AxisBase axis) {
                return String.valueOf((int) value);
            }

            @Override
            public int getDecimalDigits() {
                return 0;
            }
        });

        YAxis leftAxis = barChart.getAxisLeft();
        leftAxis.setValueFormatter(new AxisValueFormatter() {
            @Override
            public String getFormattedValue(float value, AxisBase axis) {
                return String.valueOf((int) value);
            }

            @Override
            public int getDecimalDigits() {
                return 0;
            }
        });
        leftAxis.setDrawGridLines(false);
        leftAxis.setSpaceTop(30f);
        leftAxis.setAxisMinValue(0f); // this replaces setStartAtZero(true
        barChart.getAxisRight().setEnabled(false);

        //data
        float groupSpace = 0.04f;
        float barSpace = 0.02f; // x2 dataset
        float barWidth = 0.46f; // x2 dataset
        // (0.46 + 0.02) * 2 + 0.04 = 1.00 -> interval per "group"

        int startYear = 1980;
        int endYear = 1985;


        List<BarEntry> yVals1 = new ArrayList<BarEntry>(); 
        List<BarEntry> yVals2 = new ArrayList<BarEntry>();


        for (int i = startYear; i < endYear; i++) {
            yVals1.add(new BarEntry(i, 0.4f));
        }

        for (int i = startYear; i < endYear; i++) {
            yVals2.add(new BarEntry(i, 0.7f));
        }


        BarDataSet set1, set2;

        if (barChart.getData() != null && barChart.getData().getDataSetCount() > 0) {
            set1 = (BarDataSet)barChart.getData().getDataSetByIndex(0);
            set2 = (BarDataSet)barChart.getData().getDataSetByIndex(1);
            set1.setValues(yVals1);
            set2.setValues(yVals2);
            barChart.getData().notifyDataChanged();
            barChart.notifyDataSetChanged();
        } else {
            // create 2 datasets with different types
            set1 = new BarDataSet(yVals1, "Company A");
            set1.setColor(Color.rgb(104, 241, 175));
            set2 = new BarDataSet(yVals2, "Company B");
            set2.setColor(Color.rgb(164, 228, 251));

            ArrayList<IBarDataSet> dataSets = new ArrayList<IBarDataSet>();
            dataSets.add(set1);
            dataSets.add(set2);

            BarData data = new BarData(dataSets);
            barChart.setData(data);
        }

        barChart.getBarData().setBarWidth(barWidth);
        barChart.getXAxis().setAxisMinValue(startYear);
        barChart.groupBars(startYear, groupSpace, barSpace);
        barChart.invalidate();

它的外观如何 Result

答案 2 :(得分:7)

我尝试的大部分答案都存在未对齐,非居中标签或条形图被隐藏在屏幕空间之外的问题。因此,经过一些尝试,我有一个适当的工作poc。

  

最后4行是最重要的。

    ArrayList<BarEntry> barEntries = new ArrayList<>();
    ArrayList<BarEntry> barEntries1 = new ArrayList<>();
    ArrayList<BarEntry> barEntries2 = new ArrayList<>();
    ArrayList<BarEntry> barEntries3 = new ArrayList<>();

    barEntries.add(new BarEntry(1,989.21f));
    barEntries.add(new BarEntry(2,420.22f));
    barEntries.add(new BarEntry(3,758));
    barEntries.add(new BarEntry(4,3078.97f));
    barEntries.add(new BarEntry(5,14586.96f));
    barEntries.add(new BarEntry(6,400.4f));
    barEntries.add(new BarEntry(7,5888.58f));

    barEntries1.add(new BarEntry(1,950));
    barEntries1.add(new BarEntry(2,791));
    barEntries1.add(new BarEntry(3,630));
    barEntries1.add(new BarEntry(4,782));
    barEntries1.add(new BarEntry(5,2714.54f));
    barEntries1.add(new BarEntry(6,500));
    barEntries1.add(new BarEntry(7,2173.36f));

    barEntries2.add(new BarEntry(1,900));
    barEntries2.add(new BarEntry(2,691));
    barEntries2.add(new BarEntry(3,1030));
    barEntries2.add(new BarEntry(4,382));
    barEntries2.add(new BarEntry(5,2714f));
    barEntries2.add(new BarEntry(6,5000));
    barEntries2.add(new BarEntry(7,1173f));

    barEntries3.add(new BarEntry(1,200));
    barEntries3.add(new BarEntry(2,991));
    barEntries3.add(new BarEntry(3,1830));
    barEntries3.add(new BarEntry(4,3082));
    barEntries3.add(new BarEntry(5,214));
    barEntries3.add(new BarEntry(6,5600));
    barEntries3.add(new BarEntry(7,9173));

    BarDataSet barDataSet = new BarDataSet(barEntries,"DATA SET 1");
    barDataSet.setColor(Color.parseColor("#F44336"));
    BarDataSet barDataSet1 = new BarDataSet(barEntries1,"DATA SET 2");
    barDataSet1.setColors(Color.parseColor("#9C27B0"));
    BarDataSet barDataSet2 = new BarDataSet(barEntries2,"DATA SET 3");
    barDataSet1.setColors(Color.parseColor("#e241f4"));
    BarDataSet barDataSet3 = new BarDataSet(barEntries3,"DATA SET 4");
    barDataSet1.setColors(Color.parseColor("#42f46e"));

    String[] months = new String[] {"TYPE 1", "TYPE 2", "TYPE 3", "TYPE 4"};
    BarData data = new BarData(barDataSet,barDataSet1,barDataSet2,barDataSet3);
    barChart.setData(data);

    XAxis xAxis = barChart.getXAxis();
    xAxis.setValueFormatter(new IndexAxisValueFormatter(months));
    barChart.getAxisLeft().setAxisMinimum(0);
    xAxis.setPosition(XAxis.XAxisPosition.BOTTOM);
    xAxis.setGranularity(1);
    xAxis.setCenterAxisLabels(true);
    xAxis.setGranularityEnabled(true);

    float barSpace = 0.02f;
    float groupSpace = 0.3f;
    int groupCount = 4;

    //IMPORTANT *****
    data.setBarWidth(0.15f);
    barChart.getXAxis().setAxisMinimum(0);
    barChart.getXAxis().setAxisMaximum(0 + barChart.getBarData().getGroupWidth(groupSpace, barSpace) * groupCount);
    barChart.groupBars(0, groupSpace, barSpace); // perform the "explicit" grouping
    //***** IMPORTANT

我得到的最终结果是:

Bar graph with labels fixed

答案 3 :(得分:2)

  • 第一步 在条形图中划分第一组数。如下面的示例代码显示5组。每个小组都有5个小节。

               xaxis0 = new ArrayList<>();
               for (int i = 0; i < cData.size(); i++) {
    
                   String str = cData.get(i).get("count");
                   str = str.replaceAll("\\[", "").replaceAll("\\]", "");
                   String[] finalString = str.split(",");
                   if (i == 0) {
                       for (int k = 0; k < finalString.length; k++) {
    
                           int data22 = Integer.parseInt(finalString[k]);
                           BarEntry v1e1 = new BarEntry(data22, position);
                           valueSet1.add(v1e1);
                       }
                   }
                   if (i == 1) {
                       for (int k = 0; k < finalString.length; k++) {
                           int data22 = Integer.parseInt(finalString[k] + "");
                           BarEntry v1e1 = new BarEntry(data22, position);
                           valueSet2.add(v1e1);
                       }
                   }
                   if (i == 2) {
                       for (int k = 0; k < finalString.length; k++) {
                           int data22 = Integer.parseInt(finalString[k] + "");
                           BarEntry v1e1 = new BarEntry(data22, position);
                           valueSet3.add(v1e1);
                       }
                   }
                   if (i == 3) {
                       for (int k = 0; k < finalString.length; k++) {
                           int data22 = Integer.parseInt(finalString[k] + "");
                           BarEntry v1e1 = new BarEntry(data22, position);
                           valueSet4.add(v1e1);
                       }
                   }
                   if (i == 4) {
                       for (int k = 0; k < finalString.length; k++) {
                           int data22 = Integer.parseInt(finalString[k] + "");
                           BarEntry v1e1 = new BarEntry(data22, position);
                           valueSet5.add(v1e1);
                       }
                   }
                   xaxis0.add(i, xdata.get(i).get("date"));
    
  • 步骤2在上面的代码中,您观察到5组条形码在每个值集的循环中加载数据 - ArrayList valueSet2 = new ArrayList&lt;&gt;(); 在此值集和

  • 之前初始化
  • Step3并将5组加载到Bardataset,如下所示

    `BarDataSet barDataSet1 = new BarDataSet(valueSet1,“Set1”);   barDataSet1.setColors(whitecolors);   barDataSet1.setValueTextColor(Color.WHITE);

    BarDataSet barDataSet2 = new BarDataSet(valueSet2,“Set2”);   barDataSet2.setColors(whitecolors);   barDataSet2.setValueTextColor(Color.WHITE);

    BarDataSet barDataSet3 = new BarDataSet(valueSet3,“Set3”);   barDataSet3.setColors(whitecolors);

    barDataSet3.setValueTextColor(Color.WHITE);   BarDataSet barDataSet4 = new BarDataSet(valueSet4,“Set4”);

    barDataSet4.setColors(whitecolors);   barDataSet4.setValueTextColor(Color.WHITE);

    BarDataSet barDataSet5 = new BarDataSet(valueSet5,“Set5”);   barDataSet5.setColors(whitecolors);

    barDataSet5.setValueTextColor(Color.WHITE);    dataSets = new ArrayList&lt;&gt;();    dataSets.add(barDataSet1);    dataSets.add(barDataSet2);    dataSets.add(barDataSet3);    dataSets.add(barDataSet4);    dataSets.add(barDataSet5); `

  • 最后一步需要将此数据附加到Bardata,如下面的代码

BarData data11 = new BarData(xaxis0,dataSets); data11.setGroupSpace(100F);

               holder.chart.setData(data11);

               XAxis xAxis = holder.chart.getXAxis();

               xAxis.setPosition(XAxis.XAxisPosition.BOTTOM);

               xAxis.setDrawGridLines(true);  

xAxis.setGridColor(context.getResources()的getColor(R.color.white));

               xAxis.isDrawLabelsEnabled();    

xAxis.setAxisLineColor(context.getResources()的getColor(R.color.accentColor)。);                xAxis.setTextColor(context.getResources()的getColor(R.color.white));

               xAxis.isAdjustXLabelsEnabled();

               xAxis.setAdjustXLabels(true);

               holder.chart.setDescription("");

               holder.chart.animateXY(2000, 2000);
 holder.chart.getAxisLeft().setTextColor(context.getResources().getColor(R.color.white));
               holder.chart.getAxisRight().setTextColor(context.getResources().getColor(R.color.white));
               holder.chart.setDrawGridBackground(false);
               holder.chart.getAxisRight().setEnabled(false);
               holder.chart.setDrawValueAboveBar(true);
               holder.chart.getAxisLeft().setEnabled(false);
               holder.chart.setSoundEffectsEnabled(true);
               holder.chart.getXAxis().setDrawGridLines(false);
               holder.chart.setTransitionGroup(true);
               YAxis yAxis = holder.chart.getAxisLeft();
               yAxis.setDrawGridLines(false);
               yAxis.setLabelCount(5);
               yAxis = holder.chart.getAxisRight();
               yAxis.setDrawGridLines(false);
               yAxis.setTextColor(context.getResources().getColor(R.color.white));
               Legend l =  holder.chart.getLegend();
               l.setEnabled(false);     
               Paint p = holder.chart.getPaint(Chart.PAINT_INFO);
               p.setTextSize(10);
               p.setColor(context.getResources().getColor(R.color.white));
               p.setTypeface(gotham);
               holder.chart.invalidate();
               l.setPosition(Legend.LegendPosition.BELOW_CHART_CENTER);
               l.setTextSize(200);
               yAxis.setValueFormatter(new LargeValueFormatter());

   # Thats it if you have doubt about this code ask me any time .......