Beautiful Sparkline Charts for Flutter

chart_sparkline

Beautiful sparkline charts for Flutter.

screenshot

Installation

Install the latest version from pub.

Quick Start

Import the package, create a Sparkline , and pass it your data.

import 'package:flutter/material.dart';
import 'package:chart_sparkline/chart_sparkline.dart';

void main() {
  var data = [0.0, 1.0, 1.5, 2.0, 0.0, 0.0, -0.5, -1.0, -0.5, 0.0, 0.0];
  runApp(
    MaterialApp(
      home: Scaffold(
        body: Center(
          child: Container(
            width: 300.0,
            height: 100.0,
            child: Sparkline(
              data: data,
            ),
          ),
        ),
      ),
    ),
  );
}

base example screenshot

Customization

Sparkline

PropertyDefault
lineWidth2.0
lineColorColors.lightBlue
lineGradientnull

Example:

Sparkline(
  data: data,
  lineWidth: 5.0,
  lineColor: Colors.purple,
);

lineopts example screenshot

Sparkline(
  data: data,
  lineWidth: 10.0,
  lineGradient: LinearGradient(
    begin: Alignment.topCenter,
    end: Alignment.bottomCenter,
    colors: [Colors.purple[800], Colors.purple[200]],
  ),
);

lineopts example screenshot


Points

PropertyDefault
pointsModePointsMode.none
pointSize4.0
pointColorColors.lightBlue[800]
pointIndexnull
PointsModeDescription
none (default)Do not draw individual points.
allDraw all the points in the data set.
lastDraw only the last point in the data set.
atIndexDraw one point at the index specified by pointIndex.

Example:

Sparkline(
  data: data,
  pointsMode: PointsMode.all,
  pointSize: 8.0,
  pointColor: Colors.amber,
);

all points example screenshot

Sparkline(
  data: data,
  pointsMode: PointsMode.last,
  pointSize: 8.0,
  pointColor: Colors.amber,
);

last point example screenshot

Sparkline(
  data: data,
  pointsMode: PointsMode.atIndex,
  pointIndex: 7,
  pointSize: 8.0,
  pointColor: Colors.amber,
);

Fill

PropertyDefault
fillModeFillMode.none
fillColorColors.lightBlue[200]
fillGradientnull
FillModeDescription
none (default)Do not fill, draw only the sparkline.
aboveFill the area above the sparkline.
belowFill the area below the sparkline.

Example:

Sparkline(
  data: data,
  fillMode: FillMode.below,
  fillColor: Colors.red[200],
);

fill below example screenshot

Sparkline(
  data: data,
  fillMode: FillMode.above,
  fillColor: Colors.red[200],
);

fill above example screenshot

Sparkline(
  data: data,
  fillMode: FillMode.below,
  fillGradient: LinearGradient(
    begin: Alignment.topCenter,
    end: Alignment.bottomCenter,
    colors: [Colors.red[800], Colors.red[200]],
  ),
);

fill above example screenshot

Smoothing

Sparkline(
  data: data,
  useCubicSmoothing: true,
  cubicSmoothingFactor: 0.2,
),

cubic smoothing example screenshot

Average Line

Sparkline(
  data: data,
  averageLine: true,
  averageLabel: true,
),

cubic smoothing example screenshot

first, last, highest and the lowest

Sparkline(
  data: data,
  kLine: ['max', 'min', 'first', 'last'],
),

cubic smoothing example screenshot

gridLine

Sparkline(
  gridLinelabelPrefix: '\$',
  gridLineLabelPrecision: 3,
  enableGridLines: true,
),

cubic smoothing example screenshot


Todo:

  • [x] simple sparkline
  • [x] custom line width
  • [x] custom line color
  • [x] optional rounded corners
  • [x] fill
  • [x] embiggen individual points/change color
  • [x] different points modes [all/last/none]
  • [ ] animate between two sparklines
  • [ ] animate drawing a single sparkline
  • [ ] gesture detector to select closest point to tap
  • [ ] baseline
  • [x] different fill modes [above/below/none]
  • [x] fix edge points overflowing by offsetting by lineWidth
  • [x] better corner rounding
  • [x] axis labels
  • [x] gradient shader on line paint
  • [x] gradient shader on fill paint
  • [ ] multiple overlapping sparklines on a shared axis
  • [ ] tests

Use this package as a library

Depend on it

Run this command:

With Flutter:

 $ flutter pub add chart_sparkline

This will add a line like this to your package's pubspec.yaml (and run an implicit flutter pub get):

dependencies:
  chart_sparkline: ^1.0.11

Alternatively, your editor might support flutter pub get. Check the docs for your editor to learn more.

Import it

Now in your Dart code, you can use:

import 'package:chart_sparkline/chart_sparkline.dart'; 

example/lib/main.dart

import 'package:flutter/material.dart';
import 'package:chart_sparkline/chart_sparkline.dart';

void main() {
  runApp(
    MaterialApp(
      home: Scaffold(
        body: Center(
          child: Container(
            width: 600.0,
            height: 250.0,
            child: Sparkline(
              data: [-1.5, 1 - 0, 2 - 5, -1.5, 2, 5, -2.3],
              // backgroundColor: Colors.red,
              // lineColor: Colors.lightGreen[500]!,
              // fillMode: FillMode.below,
              // fillColor: Colors.lightGreen[200]!,
              // pointsMode: PointsMode.all,
              // pointSize: 5.0,
              // pointColor: Colors.amber,
              // useCubicSmoothing: true,
              // lineWidth: 1.0,
              // gridLinelabelPrefix: '\$',
              // gridLineLabelPrecision: 3,
              // enableGridLines: true,
              averageLine: true,
              averageLabel: true,
              // kLine: ['max', 'min', 'first', 'last'],
              // // max: 50.5,
              // // min: 10.0,
              // enableThreshold: true,
              // thresholdSize: 0.1,
              // lineGradient: LinearGradient(
              //   begin: Alignment.topCenter,
              //   end: Alignment.bottomCenter,
              //   colors: [Colors.purple[800]!, Colors.purple[200]!],
              // ),
              // fillGradient: LinearGradient(
              //   begin: Alignment.topCenter,
              //   end: Alignment.bottomCenter,
              //   colors: [Colors.red[800]!, Colors.red[200]!],
              // ),
            ),
          ),
        ),
      ),
    ),
  );
} 

Download Details:

Author: biner88

Source Code: https://github.com/biner88/chart_sparkline

#chart #flutter 

Beautiful Sparkline Charts for Flutter
Aketch  Rachel

Aketch Rachel

1663227780

10 Popular Swift Chart Libraries You Can't Miss

In this Swift article, let's learn about Chart: 10 Popular Swift Chart Libraries You Can't Miss

Table of contents:

  • Charts - Beautiful charts for iOS/tvOS/OSX (port of MPAndroidChart).
  • ChartView - Swift package for displaying beautiful charts effortlessly
  • FLCharts - Easy to use and highly customizable charts library for iOS.
  • PNChart-Swift - A simple and beautiful chart lib with animation.
  • ScrollableGraphView - Adaptive scrollable graph view for iOS to visualise simple discrete datasets.
  • SwiftChart - A simple line and area charting library for iOS. Supports multiple series, partially filled series and touch events.
  • SwiftCharts - Highly customizable charts for iOS.
  • SwiftUICharts - A charts / plotting library for SwiftUI. Works on macOS, iOS, watchOS, and tvOS and has accessibility and Localization features built in.
  • TKRadarChart - A customizable radar chart.

what is swift Chart ?

Swift Charts is a powerful and concise SwiftUI framework for transforming your data into informative visualizations. With Swift Charts, you can build effective and customizable charts with minimal code.


10 Popular Swift Chart Libraries You Can't Miss

  1. Charts

Beautiful charts for iOS/tvOS/OSX! The Apple side of the crossplatform MPAndroidChart.
Just a heads up: Charts 3.0 has some breaking changes. Please read the release/migration notes.

Another heads up: ChartsRealm is now in a separate repo. Pods is also now Charts and ChartsRealm, instead of Charts/Core and Charts/Realm

One more heads up: As Swift evolves, if you are not using the latest Swift compiler, you shouldn't check out the master branch. Instead, you should go to the release page and pick up whatever suits you.

  • Xcode 14 / Swift 5.7 (master branch)
  • iOS >= 12.0 (Use as an Embedded Framework)
  • tvOS >= 12.0
  • macOS >= 10.13

Okay so there's this beautiful library called MPAndroidChart by Philipp Jahoda which has become very popular amongst Android developers, but there was no decent solution to create charts for iOS.

I've chosen to write it in Swift as it can be highly optimized by the compiler, and can be used in both Swift and ObjC project. The demo project is written in ObjC to demonstrate how it works.

An amazing feature of this library now, for Android, iOS, tvOS and macOS, is the time it saves you when developing for both platforms, as the learning curve is singleton- it happens only once, and the code stays very similar so developers don't have to go around and re-invent the app to produce the same output with a different library. (And that's not even considering the fact that there's not really another good choice out there currently...)

Having trouble running the demo?

  • ChartsDemo/ChartsDemo.xcodeproj is the demo project for iOS/tvOS
  • ChartsDemo-OSX/ChartsDemo-OSX.xcodeproj is the demo project for macOS
  • Make sure you are running a supported version of Xcode.
    • Usually it is specified here a few lines above.
    • In most cases it will be the latest Xcode version.
  • Make sure that your project supports Swift 5.0
  • Optional: Run carthage checkout in the project folder, to fetch dependencies (i.e testing dependencies).
    • If you don't have Carthage - you can get it here.

View on GitHub

2.  ChartView

Swift package for displaying charts effortlessly.

V2 Beta is here 🎉🎉🎉

V2 focuses on providing a strong and easy to use base, on which you can build your beautiful custom charts. It provides basic building blocks, like a chart view (bar, pie, line and ring chart), grid view, card view, interactive label for displaying the curent chart value. So you decide, whether you build a fully fledged interactive view, or just display a bare bone chart

How to install SwiftUI ChartView

How to create your first chart

Usage

It supports:

  • Line charts
  • Bar charts
  • Pie charts

Slack

Join our Slack channel for day to day conversation and more insights:

Slack invite link

Installation:

It requires iOS 13 and Xcode 11!

In Xcode go to File -> Swift Packages -> Add Package Dependency and paste in the repo's url: https://github.com/AppPear/ChartView

Usage:

import the package in the file you would like to use it: import SwiftUICharts

You can display a Chart by adding a chart view to your parent view:

Demo

Added an example project, with iOS, watchOS target: https://github.com/AppPear/ChartViewDemo

View on GitHub

3.  FLCharts

FLCharts is an easy-to-use library to build highly customizable bar, line and pie charts. It allows you to create your own chart bar UIView and use it to display data in the chart.
Additionally FLCharts allows you to provide a custom HighlightedView to show the highlighted bar contents on top of the chart.
Embed effortlessly your chart in a FLCard alogside with a title, an average vlue view and additional behaviours.

Requirements

  • Xcode 11 / Swift 5
  • iOS >= 11.0

Installation

FLCharts is available through SPM, CocoaPods and Carthage

Swift Package Manager

In XCode go to File -> Add Packages...

Search for https://github.com/francescoleoni98/FLCharts and click Add Package.

Select to which target you want to add it and select Add Package.

CocoaPods

FLCharts is available through CocoaPods. To install it, add the following line to your Podfile:

pod 'FLCharts'

Then run pod install

Carthage

To install it with Carthage, in your Cartfile add:

github "francescoleoni98/FLCharts"

Then run carthage update

In XCode > Build phases click the plus button on top left > New Run Script Phases.
Then in Run Script > Shell script window > add /usr/local/bin/carthage copy-frameworks.
Run Script > Input file window > add $(SRCROOT)/Carthage/Build/iOS/FLCharts.framework.

Then, go to $project_dir/Carthage/Build/iOS and drag the folder FLCharts.framework into your Xcode Project > Your Target > Frameworks, Libraries and Embedded Content.

View on GitHub

4.  PNChart-Swift

PNChart(https://github.com/kevinzhow/PNChart) Swift Implementation

Installation

This isn't on CocoaPods yet, so to install, add this to your Podfile

pod 'PNChartSwift',:git => 'https://github.com/kevinzhow/PNChart-Swift.git'

View on GitHub

5.  ScrollableGraphView

Version 4 was released which adds multiple plots, dynamic reloading of values, more reference line customisation options and various bug fixes.

You can see the major changes in the API here.

The public interface is incompatible with previous versions. If you prefer to keep using the older version, make sure to specify version 3 in your podfile or downloaded the classes from a pre-v4 release.

About

Example Application Usage

An adaptive scrollable graph view for iOS to visualise simple discrete datasets. Written in Swift. Originally written for a small personal project.

The main goal of the this graph component is to visualise simple discrete datasets and allow the the user to scroll through the graph.

Init Animation

Contribution

All pull requests are welcome. There is a list of features people would like on the issues page, ranging from simple changes to quite complex. Feel free to jump on in.

View on GitHub

6.  SwiftChart

A simple line and area charting library for iOS.

  • 📈 Line and area charts
  • 🌞 Multiple series
  • 🌒 Partially filled series
  • 🏊 Works with signed Double
  • 🖖 Touch events

Getting started

Installing SwiftChart via CocoaPods

SwiftChart is available through CocoaPods. To install it, simply add the following line to your Podfile:

pod "SwiftChart"

Installing SwiftChart manually

  1. Download SwiftChart.zip from the last release and extract its content in your project's folder.
  2. From the Xcode project, choose Add Files to ... from the File menu and add the extracted files.

What’s included in SwiftChart

The library includes:

  • the Chart main class, to initialize and configure the chart’s content, e.g. for adding series or setting up the its appearance
  • the ChartSeries class, for creating datasets and configure their appearance
  • the ChartDelegate protocol, which tells other objects about the chart’s touch events
  • the ChartColor struct, containing some predefined colors

Example

let chart = Chart()
let series = ChartSeries([0, 6, 2, 8, 4, 7, 3, 10, 8])
series.color = ChartColors.greenColor()
chart.add(series)

To run the example project, clone the repo, and run pod install from the Example directory first.

View on GitHub

7.  SwiftCharts

Easy to use and highly customizable charts library for iOS

Installation

CocoaPods

Add to your Podfile:

use_frameworks!
pod 'SwiftCharts', '~> 0.6.5'

To use master directly:

pod 'SwiftCharts', :git => 'https://github.com/i-schuetz/SwiftCharts.git'

And then:

pod install
Import the framework in your code:
import SwiftCharts

Carthage

Add to your Cartfile:

github "i-schuetz/SwiftCharts" ~> 0.6.5

Contribute

Contributions are highly appreciated! To submit one:

  1. Fork
  2. Commit changes to a branch in your fork
  3. Push your code and make a pull request

View on GitHub

8.  SwiftUICharts

A charts / plotting library for SwiftUI. Works on macOS, iOS, watchOS, and tvOS and has accessibility and Localization features built in.

Line Charts

Line Chart

Example of Line Chart

Uses LineChartData data model.

LineChart(chartData: LineChartData)

Filled Line Chart

Example of Filled Line Chart

Uses LineChartData data model.

FilledLineChart(chartData: LineChartData)

Multi Line Chart

Example of Multi Line Chart

Uses MultiLineChartData data model.

MultiLineChart(chartData: MultiLineChartData)

View on GitHub

9.  TKRadarChart

A customizable radar chart in Swift

Requirements

  • iOS 8.0+
  • Xcode 9.0
  • Swift 4.0

Installation

CocoaPods

You can use CocoaPods to install TKRadarChart by adding it to your Podfile:

platform :ios, '8.0'
use_frameworks!
pod 'TKRadarChart'

To get the full benefits import TKRadarChart wherever you import UIKit

import UIKit
import TKRadarChart

Carthage

Create a Cartfile that lists the framework and run carthage update. Follow the instructions to add $(SRCROOT)/Carthage/Build/iOS/TKRadarChart.framework to an iOS project.

github "tbxark/TKRadarChart"

Manually

  1. Download and drop TKRadarChart.swift in your project.
  2. Congratulations!

View on GitHub


Frequently asked questions about charts of Swift

  • What is a chart used for?

The main functions of a chart are to display data and invite further exploration of a topic. Charts are used in situations where a simple table won't adequately demonstrate important relationships or patterns between data points.

  • How do you create a chart in Swift?

To create a chart with Swift Charts, define your data and initialize a Chart view with marks and data properties. Then use modifiers to customize different components of the chart, like the legend, axes, and scale.

  • What is a chart data?

A chart is a graphical representation of data. Visualizing data through charts helps to uncover patterns, trends, relationships, and structure in data.

  • What is chart explain?

A chart is a graphical representation for data visualization, in which "the data is represented by symbols, such as bars in a bar chart, lines in a line chart, or slices in a pie chart". A chart can represent tabular numeric data, functions or some kinds of quality structure and provides different info.


Related videos:

Bar Charts in Swift Tutorial (Xcode 12, 2021, Swift 5) - iOS Development

Related posts:

#swift #chart 

10 Popular Swift Chart Libraries You Can't Miss

The Best K Chart in Flutter

#Introduce We forked the project from https://github.com/OpenFlutter/k_chart and add some function to meet our requirments.

all the version below are the version we released.

[0.5.1]

  • added the function that will show buy sell signal on the charts

[0.5.2]

  • support set scale-x from parameter when build widget.it solve the problem that on the flutter web,the gesture scale not work.

[0.5.3]

  • support extra line draw on the charts

[0.5.4]

  • support extra text label draw on the charts

[0.5.5]

  • support text scale parameter in text label

[0.5.6]

  • support line stroke width parameter

how to publish:

https://dart.cn/tools/pub/publishing

  1. pubspec.yaml modify
  2. CHANGELOG.md modify
  3. run command:
    1. dart pub publish --dry-run
    2. dart pub publish

Raw README.md from forked project

k_chart

Maybe this is the best k chart in Flutter.Support drag,scale,long press,fling.And easy to use.

display

image

Screenshot

Screenshot

Screenshot

gif

demo

demo

Getting Started

Install

dependencies:
  k_chart: ^0.5.0

or use latest:

k_chart:
    git:
      url: https://github.com/mafanwei/k_chart

Usage

When you change the data, you must call this:

DataUtil.calculate(datas); //This function has some optional parameters: n is BOLL N-day closing price. k is BOLL param.

use k line chart:

Container(
              height: 450,
              width: double.infinity,
              child: KChartWidget(
                chartStyle, // Required for styling purposes
                chartColors,// Required for styling purposes
                datas,// Required,Data must be an ordered list,(history=>now)
                isLine: isLine,// Decide whether it is k-line or time-sharing
                mainState: _mainState,// Decide what the main view shows
                secondaryState: _secondaryState,// Decide what the sub view shows
                fixedLength: 2,// Displayed decimal precision
                timeFormat: TimeFormat.YEAR_MONTH_DAY,
                onLoadMore: (bool a) {},// Called when the data scrolls to the end. When a is true, it means the user is pulled to the end of the right side of the data. When a
                // is false, it means the user is pulled to the end of the left side of the data.
                maDayList: [5,10,20],// Display of MA,This parameter must be equal to DataUtil.calculate‘s maDayList
                bgColor: [Colors.black, Colors.black],// The background color of the chart is gradient
                translations: kChartTranslations,// Graphic language
                volHidden: false,// hide volume
                showNowPrice: true,// show now price
                isOnDrag: (isDrag){},// true is on Drag.Don't load data while Draging.
                onSecondaryTap:(){}// on secondary rect taped.
              ),
            ),

use TrendLine(New): You can use Trendline by long-pressing and moving your finger after setting true to isTrendLine property.
use depth chart:

DepthChart(_bids, _asks, chartColors) //Note: Datas must be an ordered list,

Donate

Buy a cup of coffee for the author.

alipay

 wechat

Thanks

gwhcn/flutter_k_chart

Other

Maybe there are some bugs in this k chart,or you want new indicators,you can create a pull request.I will happy to accept it and I hope we can make it better.

The version of fork

Use this package as a library

Depend on it

Run this command:

With Flutter:

 $ flutter pub add k_chart_pw

This will add a line like this to your package's pubspec.yaml (and run an implicit flutter pub get):

dependencies:
  k_chart_pw: ^0.5.6

Alternatively, your editor might support flutter pub get. Check the docs for your editor to learn more.

Import it

Now in your Dart code, you can use:

import 'package:k_chart_pw/chart_style.dart';
import 'package:k_chart_pw/chart_translations.dart';
import 'package:k_chart_pw/depth_chart.dart';
import 'package:k_chart_pw/entity/candle_entity.dart';
import 'package:k_chart_pw/entity/cci_entity.dart';
import 'package:k_chart_pw/entity/depth_entity.dart';
import 'package:k_chart_pw/entity/extra_buy_sell_signal.dart';
import 'package:k_chart_pw/entity/extra_line.dart';
import 'package:k_chart_pw/entity/extra_text_label.dart';
import 'package:k_chart_pw/entity/index.dart';
import 'package:k_chart_pw/entity/info_window_entity.dart';
import 'package:k_chart_pw/entity/k_entity.dart';
import 'package:k_chart_pw/entity/k_line_entity.dart';
import 'package:k_chart_pw/entity/kdj_entity.dart';
import 'package:k_chart_pw/entity/macd_entity.dart';
import 'package:k_chart_pw/entity/rsi_entity.dart';
import 'package:k_chart_pw/entity/rw_entity.dart';
import 'package:k_chart_pw/entity/volume_entity.dart';
import 'package:k_chart_pw/extension/map_ext.dart';
import 'package:k_chart_pw/extension/num_ext.dart';
import 'package:k_chart_pw/flutter_k_chart.dart';
import 'package:k_chart_pw/k_chart_widget.dart';
import 'package:k_chart_pw/renderer/base_chart_painter.dart';
import 'package:k_chart_pw/renderer/base_chart_renderer.dart';
import 'package:k_chart_pw/renderer/chart_painter.dart';
import 'package:k_chart_pw/renderer/index.dart';
import 'package:k_chart_pw/renderer/main_renderer.dart';
import 'package:k_chart_pw/renderer/secondary_renderer.dart';
import 'package:k_chart_pw/renderer/vol_renderer.dart';
import 'package:k_chart_pw/utils/data_util.dart';
import 'package:k_chart_pw/utils/date_format_util.dart';
import 'package:k_chart_pw/utils/index.dart';
import 'package:k_chart_pw/utils/number_util.dart'; 

example/lib/main.dart

import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:http/http.dart' as http;
import 'package:k_chart_pw/chart_style.dart';
import 'package:k_chart_pw/chart_translations.dart';
import 'package:k_chart_pw/entity/extra_buy_sell_signal.dart';
import 'package:k_chart_pw/entity/extra_line.dart';
import 'package:k_chart_pw/entity/extra_text_label.dart';
import 'package:k_chart_pw/flutter_k_chart.dart';
import 'package:k_chart_pw/k_chart_widget.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.green,
      ),
      home: MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key? key, this.title}) : super(key: key);

  final String? title;

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  List<KLineEntity>? datas;
  List<ExtraBuySellSignal>? extraBuySellSignals = [];
  List<ExtraLine> extraLineList = [];
  List<ExtraTextLabel> extraTextLabel = [];
  bool showLoading = true;
  MainState _mainState = MainState.MA;
  bool _volHidden = false;
  SecondaryState _secondaryState = SecondaryState.MACD;
  bool isLine = true;
  bool isChinese = true;
  bool _hideGrid = false;
  bool _showNowPrice = true;
  List<DepthEntity>? _bids, _asks;
  bool isChangeUI = false;
  bool _isTrendLine = false;

  ChartStyle chartStyle = ChartStyle();
  ChartColors chartColors = ChartColors();

  @override
  void initState() {
    super.initState();
    getData('1day');
    rootBundle.loadString('assets/depth.json').then((result) {
      final parseJson = json.decode(result);
      final tick = parseJson['tick'] as Map<String, dynamic>;
      final List<DepthEntity> bids = (tick['bids'] as List<dynamic>)
          .map<DepthEntity>(
              (item) => DepthEntity(item[0] as double, item[1] as double))
          .toList();
      final List<DepthEntity> asks = (tick['asks'] as List<dynamic>)
          .map<DepthEntity>(
              (item) => DepthEntity(item[0] as double, item[1] as double))
          .toList();
      initDepth(bids, asks);
    });
  }

  void initDepth(List<DepthEntity>? bids, List<DepthEntity>? asks) {
    if (bids == null || asks == null || bids.isEmpty || asks.isEmpty) return;
    _bids = [];
    _asks = [];
    double amount = 0.0;
    bids.sort((left, right) => left.price.compareTo(right.price));
    //累加买入委托量
    bids.reversed.forEach((item) {
      amount += item.vol;
      item.vol = amount;
      _bids!.insert(0, item);
    });

    amount = 0.0;
    asks.sort((left, right) => left.price.compareTo(right.price));
    //累加卖出委托量
    asks.forEach((item) {
      amount += item.vol;
      item.vol = amount;
      _asks!.add(item);
    });
    setState(() {});
  }

  @override
  Widget build(BuildContext context) {
    return ListView(
      shrinkWrap: true,
      children: <Widget>[
        Stack(children: <Widget>[
          Container(
            height: 450,
            width: double.infinity,
            child: KChartWidget(
              datas,
              chartStyle,
              chartColors,
              isLine: isLine,
              onSecondaryTap: () {
                print('SSecondary Tap');
              },
              default_scale_x: 0.4,
              extraBuySellSignals: this.extraBuySellSignals,
              extraLineList: this.extraLineList,
              extraTextLabelList: this.extraTextLabel,
              isTrendLine: _isTrendLine,
              mainState: _mainState,
              volHidden: _volHidden,
              secondaryState: _secondaryState,
              fixedLength: 2,
              timeFormat: TimeFormat.YEAR_MONTH_DAY,
              translations: kChartTranslations,
              showNowPrice: _showNowPrice,
              //`isChinese` is Deprecated, Use `translations` instead.
              isChinese: isChinese,
              hideGrid: _hideGrid,
              isTapShowInfoDialog: false,
              maDayList: [1, 100, 1000],
            ),
          ),
          if (showLoading)
            Container(
                width: double.infinity,
                height: 450,
                alignment: Alignment.center,
                child: const CircularProgressIndicator()),
        ]),
        buildButtons(),
        if (_bids != null && _asks != null)
          Container(
            height: 230,
            width: double.infinity,
            child: DepthChart(_bids!, _asks!, chartColors),
          )
      ],
    );
  }

  Widget buildButtons() {
    return Wrap(
      alignment: WrapAlignment.spaceEvenly,
      children: <Widget>[
        button("Time Mode", onPressed: () => isLine = true),
        button("K Line Mode", onPressed: () => isLine = false),
        button("TrendLine", onPressed: () => _isTrendLine = !_isTrendLine),
        button("Line:MA", onPressed: () => _mainState = MainState.MA),
        button("Line:BOLL", onPressed: () => _mainState = MainState.BOLL),
        button("Hide Line", onPressed: () => _mainState = MainState.NONE),
        button("Secondary Chart:MACD",
            onPressed: () => _secondaryState = SecondaryState.MACD),
        button("Secondary Chart:KDJ",
            onPressed: () => _secondaryState = SecondaryState.KDJ),
        button("Secondary Chart:RSI",
            onPressed: () => _secondaryState = SecondaryState.RSI),
        button("Secondary Chart:WR",
            onPressed: () => _secondaryState = SecondaryState.WR),
        button("Secondary Chart:CCI",
            onPressed: () => _secondaryState = SecondaryState.CCI),
        button("Secondary Chart:Hide",
            onPressed: () => _secondaryState = SecondaryState.NONE),
        button(_volHidden ? "Show Vol" : "Hide Vol",
            onPressed: () => _volHidden = !_volHidden),
        button("Change Language", onPressed: () => isChinese = !isChinese),
        button(_hideGrid ? "Show Grid" : "Hide Grid",
            onPressed: () => _hideGrid = !_hideGrid),
        button(_showNowPrice ? "Hide Now Price" : "Show Now Price",
            onPressed: () => _showNowPrice = !_showNowPrice),
        button("Customize UI", onPressed: () {
          setState(() {
            this.isChangeUI = !this.isChangeUI;
            if (this.isChangeUI) {
              chartColors.selectBorderColor = Colors.red;
              chartColors.selectFillColor = Colors.red;
              chartColors.lineFillColor = Colors.red;
              chartColors.kLineColor = Colors.yellow;
            } else {
              chartColors.selectBorderColor = Color(0xff6C7A86);
              chartColors.selectFillColor = Color(0xff0D1722);
              chartColors.lineFillColor = Color(0x554C86CD);
              chartColors.kLineColor = Color(0xff4C86CD);
            }
          });
        }),
      ],
    );
  }

  Widget button(String text, {VoidCallback? onPressed}) {
    return TextButton(
      onPressed: () {
        if (onPressed != null) {
          onPressed();
          setState(() {});
        }
      },
      child: Text(text),
      style: TextButton.styleFrom(
        primary: Colors.white,
        minimumSize: const Size(88, 44),
        padding: const EdgeInsets.symmetric(horizontal: 16.0),
        shape: const RoundedRectangleBorder(
          borderRadius: BorderRadius.all(Radius.circular(2.0)),
        ),
        backgroundColor: Colors.blue,
      ),
    );
  }

  void getData(String period) {
    /*
     * 可以翻墙使用方法1加载数据,不可以翻墙使用方法2加载数据,默认使用方法1加载最新数据
     */
    final Future<String> future = getChatDataFromInternet(period);
    // final Future<String> future = getChatDataFromJson();
    future.then((String result) {
      solveChatData(result);
    }).catchError((_) {
      showLoading = false;
      setState(() {});
      print('### datas error $_');
    });
  }

  //获取火币数据,需要翻墙
  Future<String> getChatDataFromInternet(String? period) async {
    var url =
        'https://api.huobi.br.com/market/history/kline?period=${period ?? '1day'}&size=300&symbol=btcusdt';
    late String result;
    final response = await http.get(Uri.parse(url));
    if (response.statusCode == 200) {
      result = response.body;
    } else {
      print('Failed getting IP address');
    }
    return result;
  }

  // 如果你不能翻墙,可以使用这个方法加载数据
  Future<String> getChatDataFromJson() async {
    return rootBundle.loadString('assets/chatData.json');
  }

  void solveChatData(String result) {
    final Map parseJson = json.decode(result) as Map<dynamic, dynamic>;
    final list = parseJson['data'] as List<dynamic>;
    datas = list
        .map((item) => KLineEntity.fromJson(item as Map<String, dynamic>))
        .toList()
        .reversed
        .toList()
        .cast<KLineEntity>();
    DataUtil.calculate(datas!);
    var theData = datas;

    if (theData != null && theData.length > 10) {
      var theTime = theData[theData.length - 2].time;
      if (theTime != null) {
        extraBuySellSignals?.add(
            ExtraBuySellSignal(time: theTime, isBuy: true, isSell: false));
      }

      theTime = theData[theData.length - 8].time;
      if (theTime != null) {
        extraBuySellSignals?.add(
            ExtraBuySellSignal(time: theTime, isBuy: false, isSell: true));
      }
    }

    extraLineList.add(ExtraLine(
        startIndex: 0,
        startPrice: 29888,
        endIndex: theData != null ? theData.length - 1 : 100,
        endPrice: 60000,
        color: Colors.blue,
        strokeWidth: 2.0));

    extraLineList.add(ExtraLine(
        startIndex: 0,
        startPrice: 50000,
        endIndex: 100,
        endPrice: 40000,
        color: Colors.amberAccent));

    extraTextLabel.add(ExtraTextLabel(
        startIndex: 10, startPrice: 50000, textContent: " world you "));

    extraTextLabel.add(ExtraTextLabel(
        startIndex: 100, startPrice: 50000, textContent: " hello you "));

    showLoading = false;
    setState(() {});
  }
} 

Download Details:

Author: pecpwee

Source Code: https://github.com/pecpwee/k_chart

#flutter #chart 

The Best K Chart in Flutter
Nat  Grady

Nat Grady

1661577600

GoogleVis: Interface Between R and The Google Chart tools

googleVis 

The googleVis package provides an interface between R and the Google's charts tools. It allows users to create web pages with interactive charts based on R data frames. Charts are displayed locally via the R HTTP help server. A modern browser with Internet connection is required. The data remains local and is not uploaded to Google.

Installation

You can install the stable version from CRAN:

install.packages('googleVis')

Usage

library(googleVis)
?googleVis
demo(googleVis)

See the googleVis package vignette for more details. For a brief introduction read the five page R Journal article.

Check out the examples from the googleVis demo.

Please read Google's Terms of Use before you start using the package.

Download Details:

Author: Mages
Source Code: https://github.com/mages/googleVis 

#r #google #chart #tools 

GoogleVis: Interface Between R and The Google Chart tools
Nat  Grady

Nat Grady

1661518168

Leaflet.minicharts: Minicharts for Dynamic Leaflet Maps

leaflet.minicharts

Minicharts for dynamic {leaflet} maps    

For a few years now, it has become easy to create interactive maps with R thanks to the package leaflet by the Rstudio team. Nevertheless, it only provides only a few functions to create basic shapes on a map, so the information that can be represented on a single map is limited: if you have some data associated to some points, you can only represent at most two variables by drawing circles and changing their radius and color according to data.

leaflet.minicharts is an R package that provides two functions to add and update small charts on an interactive maps created with the package leaflet. These charts can be used to represent as many variables as desired associated to geographical points. Currently, three types of chart are supported: barcharts (the default), pie charts and polar area charts (with two variants: "polar-area" and "polar-radius", where values are represented respectively by the area or the radius of the slices).

Here are screenshots of sample outputs:

Installation and usage

You can install the package from CRAN:

install.packages("leaflet.minicharts")

To see how simple it is to use this package, have a look at the package vignette.

Contributing

Contributions to the library are welcome and can be submitted in the form of pull requests to this repository:

https://github.com/rte-antares-rpackage/leaflet.minicharts

This package contains some javascript code. To modify it requires npm and grunt. First modify files in the javascript folder. Then in a terminal, run the following commands:

cd javascript
npm install
grunt build

Download Details:

Author: rte-antares-rpackage
Source Code: https://github.com/rte-antares-rpackage/leaflet.minicharts 

#r #javascript #chart #leaflet 

Leaflet.minicharts: Minicharts for Dynamic Leaflet Maps
Reid  Rohan

Reid Rohan

1660672380

Wunderbar: Simple Horizontal Bar Chart Printer for Your Terminal

@gribnoysup/wunderbar

Have you ever wanted to print some pretty bar charts in your terminal? You are in the right place!

wunder-bar-cli-all

Wunderbar can print horisontal bar chart with legend and chart scale straight to your terminal. Or you can use it as a module in your code and get all the building blocks to print chart yourself.

Wunderbar uses partial block characters (▏▎▍▌▋▊▉█) to print the most precise charts possible:

wunder-bar-precise

Use in terminal

echo "[1, 2, 3, 4, 5]" | npx @gribnoysup/wunderbar --min 0

wunder-bar-echo-json

cat data.json | npx @gribnoysup/wunderbar --min 0

wunder-bar-cat-file

Use in your code

npm i --save @gribnoysup/wunderbar
const wunderbar = require('@gribnoysup/wunderbar');
const data = require('./data.json');

const printData = () => {
  const { chart, legend, scale, __raw } = wunderbar(data, {
    min: 0,
    length: 42,
  });

  console.log();
  console.log(chart);
  console.log();
  console.log(scale);
  console.log();
};

printData();

Limitations

Wunderbar supports only node >= 6

Wunderbar uses chalk.hex to add color to your charts. Chalk is pretty smart to downgrade the color if it is not supported by your terminal, but output may vary in different terminals.

API

wunderbar(values, [options]) ⇒ OutputValue

ParamTypeDefaultDescription
valuesArray<InputValue> Values to draw on a chart
[options]Object Chart drawing options
[options.min]numbermin value from valuesMin chart value (inclusive)
[options.max]numbermax value from valuesMax chart value (inclusive)
[options.length]numberterminal widthChart length
[options.sort]"min" | "max" | "none" | (a: NormalizedValue, b: NormalizedValue) => number"none"Sort method for chart values
[options.randomColorOptions]Object{}[randomColor options][2] for color generation
[options.format]string | (a: number) => string"0.00"Value format method. String values are [Numeral.js format][7] strings

All options are also supported in the cli version:

echo "[1000, 3000, 5000, 7000, 9000, 11000]" | \
  npx @gribnoysup/wunderbar --min 0 --max 15000 --length 42 --sort min --randomColorOptions '{ "seed": "unicorn" }' --format "0a"

wunder-bar-cli-all

Types

InputValue : { value: number, color?: string, label?: string } | number | string

OutputValue : { legend: string, scale: string, chart: string, __raw: RawData }

RawData : { chartLength: number, minValue: number, minValueFormatted: string, maxValue: number, maxValueFormatted: string, normalizedValues: NormalizedValue[] }

NormalizedValue : { normalizedValue: number, rawValue: number, formattedValue: string, color: string, label: string, lineLength: number, chartBar: string, coloredChartBar: string }

Download Details:

Author: Gribnoysup
Source Code: https://github.com/gribnoysup/wunderbar 
License: MIT license

#javascript #cli #node #chart 

Wunderbar: Simple Horizontal Bar Chart Printer for Your Terminal
Dexter  Goodwin

Dexter Goodwin

1660500540

Component for Displaying an Org Chart For A Large Organization

React Organizational Chart

React component for displaying organizational charts.

This component is based on coreseekdev/react-org-chart. On top of it, we added a few customization to fulfill our requirements.

View demo

Features

From the original package:

  • High-performance D3-based SVG rendering
  • Lazy-load children with a custom function
  • Handle up to 1 million collapsed nodes and 5,000 expanded nodes
  • Pan (drag and drop)
  • Zoom in zoom out (with mouse wheel/scroll)

What we added:

  • Lazy-load of parents (go up in the tree)
  • Zoom in, zoom out and zoom buttons.
  • Download orgchart as image or PDF

React Props

propertytypedescriptionexample
treeObjectNested data model with some of all the employees in the company (Required)See sample below.
nodeWidthNumberWidth of the component for each individual (Optional)180
nodeHeightNumberHeight of the component for each individual (Optional)100
nodeSpacingNumberSpacing between each of the nodes in the chart (Optional)12
animationDurationNumberDuration of the animations in milliseconds (Optional)350
lineTypeStringType of line that connects the nodes to each other (Optional)“angle” “curve”
downloadImageIdStringId of the DOM element that, on click, will trigger the download of the org chart as PNG. OrgChart will bind the click event to the DOM element with this ID (Optional)"download-image" (default)
downloadPdfIdStringId of the DOM element that, on click, will trigger the download of the org chart as PDF. OrgChart will bind the click event to the DOM element with this ID (Optional) (Optional)"download-pdf" (default)
zoomInIdStringId of the DOM element that, on click, will trigger a zoom of the org chart. OrgChart will bind the click event to the DOM element with this ID (Optional) (Optional)"zoom-in" (default)
zoomOutIdStringId of the DOM element that, on click, will trigger the zoom out of the org chart. OrgChart will bind the click event to the DOM element with this ID (Optional)"zoom-out" (default)
zoomExtentIdStringId of the DOM element that, on click, will display whole org chart svg fit to screen. OrgChart will bind the click event to the DOM element with this ID(Optional)"zoom-extent" (default)
loadParent(personData)FunctionLoad parent with one level of children (Optional)See usage below
loadChildren (personData)FunctionLoad the children of particular node (Optional)See usage below
onConfigChangeFunctionTo set the latest config to state on changeSee usage below
loadConfigFunctionPass latest config from state to OrgChartSee usage below
loadImage(personData)FunctionTo get image of person on API call (Optional)See usage below

Sample tree data

{
  id: 1,
  person: {
    id: 1,
    avatar: 'https://s3.amazonaws.com/uifaces/faces/twitter/spbroma/128.jpg',
    department: '',
    name: 'Jane Doe',
    title: 'CEO',
    totalReports: 5
  },
  hasChild: true,
  hasParent: false,
  isHighlight: true,
  children: [
    {
    id: 2,
    person: {
      id: 2,
      avatar: 'https://s3.amazonaws.com/uifaces/faces/twitter/spbroma/128.jpg',
      department: '',
      name: 'John Foo',
      title: 'CTO',
      totalReports: 0
    },
    hasChild: false,
    hasParent: true,
    isHighlight: false,
    children: []
  },
  ...
  ]
}

Usage

You have a complete working example in the examples/ folder

import React from 'react'
import OrgChart from '@unicef/react-org-chart'

handleLoadConfig = () => {
   const { config } = this.state
   return config
}

render(){
  return (
    <OrgChart
      tree={tree}
      downloadImageId="download-image"
      downloadPdfId="download-pdf"
      onConfigChange={config => {
        // Setting latest config to state
        this.setState({ config: config })
      }}
      loadConfig={d => {
         // Called from d3 to get latest version of the config. 
        const config = this.handleLoadConfig(d)
        return config
      }}
      loadParent={personData => {
        // getParentData(): To get the parent data from API
        const loadedParent = this.getParentData(personData)
        return Promise.resolve(loadedParent)
      }}
      loadChildren={personData => {
        // getChildrenData(): To get the children data from API
        const loadedChildren = this.getChildrenData(personData)
        return Promise.resolve(loadedChildren)
      }}
      loadImage={personData => {
        // getImage(): To get the image from API
        const image = getImage(personData.email)
        return Promise.resolve(image)
      }}
    />
  )
}

Development

git clone https://github.com/unicef/react-org-chart.git
cd react-org-chart
npm install

To build in watch mode:

npm start

To build for production

npm run build

Running the example:

cd example/
npm install # Only first time
npm start

To deploy the example to gh-pages site

npm run deploy

About UNICEF

UNICEF works in over 190 countries and territories to protect the rights of every child. UNICEF has spent more than 70 years working to improve the lives of children and their families. In UNICEF, we believe all children have a right to survive, thrive and fulfill their potential – to the benefit of a better world.

Donate

Collaborations and support

Just fork the project and make a pull request. You may also consider donating.

Download Details:

Author: Unicef
Source Code: https://github.com/unicef/react-org-chart 
License: UNICEF

#react #chart 

Component for Displaying an Org Chart For A Large Organization

A High-performance Full Featured Candlesticks Chart for All Platforms

candlesticks

A high-performance full featured candlesticks chart for all platforms!

web demo:
Binance Candles
Binance Candles Github Repository

Preview

IOSmacOS

Installation

  1. Add this to your package's pubspec.yaml file:
dependencies:
  candlestix: ^2.2.0
  1. Get the package using your IDE's GUI or via command line with
$ flutter pub get

Usage

import 'package:candlestix/candlestix.dart';

Candle

[Candle] class contains six required variables that hold a single candle data: date, high, low, open, close and volume.

final candle =  Candle(date: DateTime.now(), open: 1780.36, high: 1873.93, low: 1755.34, close: 1848.56, volume: 0);

Candlesticks

[Candlesticks] widget requires a list of candles, the arrangement of the candles array should be such that the newest item is in position 0, onLoadMoreCandles is a nullable callback which calls whenever the last candle gets visible. and in case you whant to add more actions in top toolbar like Binance Candles, you can make your custom [ToolBarAction] and add it to actions parameter.

🍺 pull requests are welcome!

Use this package as a library

Depend on it

Run this command:

With Flutter:

 $ flutter pub add candlestix

This will add a line like this to your package's pubspec.yaml (and run an implicit flutter pub get):

dependencies:
  candlestix: ^2.2.1

Alternatively, your editor might support flutter pub get. Check the docs for your editor to learn more.

Import it

Now in your Dart code, you can use:

import 'package:candlestix/candlestix.dart'; 

example/lib/main.dart

import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:candlestix/candlesticks.dart';
import 'package:http/http.dart' as http;

void main() {
  runApp(MyApp());
}

class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  List<Candle> candles = [];
  bool themeIsDark = false;

  @override
  void initState() {
    fetchCandles().then((value) {
      setState(() {
        candles = value;
      });
    });
    super.initState();
  }

  Future<List<Candle>> fetchCandles() async {
    final uri = Uri.parse(
        "https://api.binance.com/api/v3/klines?symbol=BTCUSDT&interval=1h");
    final res = await http.get(uri);
    return (jsonDecode(res.body) as List<dynamic>)
        .map((e) => Candle.fromJson(e))
        .toList()
        .reversed
        .toList();
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      theme: themeIsDark ? ThemeData.dark() : ThemeData.light(),
      debugShowCheckedModeBanner: false,
      home: Scaffold(
        appBar: AppBar(
          title: Text("BTCUSDT 1H Chart"),
          actions: [
            IconButton(
              onPressed: () {
                setState(() {
                  themeIsDark = !themeIsDark;
                });
              },
              icon: Icon(
                themeIsDark
                    ? Icons.wb_sunny_sharp
                    : Icons.nightlight_round_outlined,
              ),
            )
          ],
        ),
        body: Center(
          child: Candlesticks(
            candles: candles,
            annotations: [],
          ),
        ),
      ),
    );
  }
} 

Download Details:

Author: robomotionio

Source Code: https://github.com/robomotionio/candlesticks

#flutter #chart #platform 

A High-performance Full Featured Candlesticks Chart for All Platforms
Reid  Rohan

Reid Rohan

1658334600

Lit-line: A Minimal Line Chart Web Component for Modern Websites

Overview

lit-line is a minimal line chart web component for modern website.

why?

  • small: less than 6kb (gzip)
  • fast: designed for rendering thousand of points with ease (thanks to the awesome lit-html)
  • multi-lines support: lines with the same unit are scaled together
  • fully responsive: high data density are merged for better readability
  • interactive: user can interact with lines (Desktop and mobile)
  • agnostic: can be used with your favorite plateform or library

try it!

picture alt

Installation

$ npm install lit-line

or

<script
  type="module"
  src="https://unpkg.com/lit-line@{version}/dist/lit-line.js"
></script>

quick start

<lit-line id="chart"></lit-line>

<script>
  await customElements.whenDefined('lit-line');
  const chart = document.getElementById('chart');

  chart.data = [
    {
      color: '#112',
      points: [
        {time: 1982, value: 1112},
        {time: 1983, value: 2705},
        {time: 2014, value: 1303},
        {time: 2016, value: 2605},
      ]
    }
  ];
</script>

quick start using lit-html (declarative)

import 'lit-line';


<lit-line id="chart" .data=${
  [{
    color: '#112',
    points: [
      {time: 1982, value: 1112},
      {time: 1983, value: 2705},
      {time: 2014, value: 1303},
      {time: 2016, value: 2605},
  ]}></lit-line>

Dataset format

Lit-Line .data property accepts Serie arrays such as:

interface Serie {
  color?: string; // the line color (default: #224)
  unit?: string; // series with the same unit are scaled together
  points: { time: number; value: number }[]; // a list of data points
}

Customization

To change the time selection appearance when the user interact with chart:

lit-line {
  --lit-line-selected-time--opacity: 0.4;
  --lit-line-selected-time--color: red;
  --lit-line-selected-time--width: 2;
}

Todo next

  • Add more test cases:
    • testing browser resize
    • testing user interactions
    • testing multi lines
  • Improve jsDoc
  • Enhance customization (need feedback here!)

Author: Apinet
Source Code: https://github.com/apinet/lit-line 
License: MIT license

#javascript #line #svg #chart 

Lit-line: A Minimal Line Chart Web Component for Modern Websites
Reid  Rohan

Reid Rohan

1658332920

QuickChart: Chart Image and QR Code Web API

QuickChart

QuickChart is a service that generates images of charts from a URL. Because these charts are simple images, they are very easy to embed in non-dynamic environments such as email, SMS, chat rooms, and so on.

See it in action

The chart image generation service is available online at QuickChart.io. There is an interactive editor that allows you to adjust inputs and build images.

Here's an example chart that is defined completely by its URL:

The above image can be included anywhere you like. Here is its URL:

[https://quickchart.io/chart?width=500&height=300&c={type:'bar',data:{labels:['January','February','March','April','May'],datasets:[{label:'Dogs',data:[50,60,70,180,190]},{label:'Cats',data:[100,200,300,400,500]}]}}](https://quickchart.io/chart?width=500&height=300&c={type:'bar',data:{labels:['January','February','March','April','May'],datasets:[{label:'Dogs',data:[50,60,70,180,190]},{label:'Cats',data:[100,200,300,400,500]}]}})

As you can see, the Javascript or JSON object contained in the URL defines the chart:

{
  type: 'bar',
  data: {
    labels: ['January', 'February', 'March', 'April', 'May'],
    datasets: [{
      label: 'Dogs',
      data: [ 50, 60, 70, 180, 190 ]
    }, {
      label: 'Cats',
      data: [ 100, 200, 300, 400, 500 ]
    }]
  }
}

Go to the full QuickChart documentation to learn more. See gallery for examples.

Configuring your chart

The chart configuration object is based on the popular Chart.js API. Check out the Chart.js documentation for more information on how to customize your chart, or see QuickChart documentation for API options.

QuickChart includes many Chart.js plugins that allow you to add chart annotations, data labels, and more: chartjs-plugin-datalabels, chartjs-plugin-annotation, chartjs-plugin-piechart-outlabels, chartjs-chart-radial-gauge, chartjs-chart-box-and-violin-plot , chartjs-plugin-doughnutlabel, and chartjs-plugin-colorschemes.

Chart.js v3

Chart.js v3 is supported via the version parameter (documentation to read more about parameters). Custom chart plugins such as annotations and outlabels are disabled for >= 3.0.0 due to lack of support.

Each QuickChart instance should use 1 specific version of the Chart.js library. Mixing and matching versions (e.g., rendering a v2 chart followed by a v3 chart) is not well supported.

QR Codes

The service also produces QR codes. For example, https://quickchart.io/qr?text=Hello+world produces:

https://quickchart.io/qr?text=Hello+world

The /qr endpoint has the following query parameters:

  • text - QR code data (required)
  • format - png or svg (png default)
  • size - size in pixels of one side of the square image (defaults to 150)
  • margin - size of the QR image margin in modules (defaults to 4)
  • ecLevel - Error correction level (defaults to M)
  • dark - Hex color code for dark portion of QR code (defaults to 000000)
  • light - Hex color code for light portion of QR code (defauls to ffffff)

Client libraries

Dependencies and Installation

Chart generation requires several system dependencies: Cairo, Pango, libjpeg, and libgif. Run ./scripts/setup.sh for a fresh install on Linux machines (note that this also installs yarn, node, and monit).

To install system dependencies on Mac OSX, you probably just need to brew install cairo pango libffi. You may have to export PKG_CONFIG_PATH="/usr/local/opt/libffi/lib/pkgconfig" before installing node packages.

Once you have system dependencies installed, run yarn install or npm install to install the node dependencies.

Running the server

node index.js will start the server on port 3400. Set your PORT environmental variable to change this port.

Docker

A docker image is available on dockerhub at ianw/quickchart.

Building

Dockerfile sets up a server that provides chart and qr code web endpoints. It is not parameterized and provides exactly the same web service as https://quickchart.io/.

The Docker image for this project is built with the following command:

docker build -t ianw/quickchart .

Running

The server runs on port 3400 within the container. This command will expose the server on port 8080 on your host (hostport:containerport):

docker run -p 8080:3400 ianw/quickchart

The production service on QuickChart.io runs behind an NGINX reverse proxy via the config available in nginx/. You should modify this for your own purposes or use a docker image such as nginx-proxy. Of course, you can always serve traffic directly from Node, but it is generally best practice to put something in front of it.

Deploy

By following the Docker instructions above, you can deploy the service to any platform that supports running containers.

Clicking the following will execute the Docker build on a remote machine and deploy the service to Google Cloud Run an automatically scaled and pay-per-request environment:

Run on Google Cloud

Health and Monitoring

QuickChart has two API endpoints to determine the health of the service.

/healthcheck is a basic endpoint that returns a 200 status code and a JSON object that looks like this: {"success":true,"version":"1.1.0"}.

A second endpoint, /healthcheck/chart returns a 302 status code and redirects to a chart with random attributes. Although it is a more expensive endpoint, it can be useful for cache busting or testing chart rendering.

The hosted QuickChart service uses monit to make sure the service is online and restart it if not. An example monit config is in test/monit.

Chart.js v3

Chart.js v3 is supported via the version parameter (see documentation to read more about the version parameter). Some custom chart plugins are disabled for >= 3.0.0 due to lack of support.

If you are self-hosting QuickChart, each QuickChart instance should use a single version of the Chart.js library. Mixing and matching versions (e.g., rendering a v2 chart followed by a v3 chart) is not well supported.

Securing your self-hosted instance

If you are hosting QuickChart youself, take care not to expose the service to untrusted parties. Because Chart.js configs may contain arbitrary Javascript, it is necessary to properly sandbox your QuickChart instance.

Author: typpo
Source Code: https://github.com/typpo/quickchart 
License: AGPL-3.0 license

#javascript #chart 

QuickChart: Chart Image and QR Code Web API
Reid  Rohan

Reid Rohan

1658329080

Plottable: A Library Of Modular Chart Components Built on D3

Plottable.js 

Overview

Plottable.js is a library of chart components for creating flexible, custom charts for websites. It is built on top of D3.js and provides higher-level pieces, like plots, gridlines, and axes. As such, it's easier to quickly build charts than with D3, and the charts are much more flexible than standard-template charts provided by charting libraries. You can think of Plottable as a "D3 for Charts" — it is not a charting library but rather a library of chart components. Check out examples of Plottable on our website's examples page.

Philosophy

Plottable's core philosophy is "Composition over Configuration", so a lot of the API flexibility is in choosing which Components to use, and how to arrange them in Tables, rather than setting high-level properties on the charts. If you find you need a feature that doesn't exist, consider writing a new Component that implements the functionality. This way, you can get your custom functionality and still benefit from the rest of the library.

Plottable.js is being developed by Palantir Technologies. It's developed in TypeScript and distributed in ES5 JavaScript.

Quick Start

Upgrading to v1.0.0

If you are upgrading from a pre-v1.0.0 version of Plottable to v1.0.0 or later, please use the Upgrade Guide on the wiki.

We Want To Help!

If you run into any problems using Plottable, please let us know. We want Plottable to be easy-to-use, so if you are getting confused, it is our fault, not yours. Create an issue and we'll be happy to help you out, or drop by our Gitter room.

Development

  • Clone the repo
  • Install global dependencies sudo npm install grunt grunt-cli typescript -g
  • Install local dependencies npm install
  • Run grunt and it will spin up a server (pointed at localhost:9999) and begin compiling the typescript code

Contributing

  • Write your code
  • Add tests for new functionality, and please add some quicktests too
  • Run grunt test and verify it completes with no warnings or failures
  • Commit new files, including the updated built files like plottable.js and plottable.d.ts
  • Fill out the Personal or Corporate Contributor License Agreement and send it to opensource@palantir.com
    • You can do this easily on a Mac by using the Tools - Annotate - Signature feature in Preview.
  • Submit a pull request

Author: Palantir
Source Code: https://github.com/palantir/plottable 
License: MIT license

#javascript #d3 #chart #typescript 

Plottable: A Library Of Modular Chart Components Built on D3
Reid  Rohan

Reid Rohan

1658327220

JQuery-linechart: JQuery Plugin for Creating Charts

JQuery Linechart

JQuery plugin for building a linechart. Chart ruler completely on HTML/CSS/JS. Bar chart, calendar view visualisation. Diagram, graph, pyramid visualisation of large datasets. Showreel. The source for this module is in the main repo. Please create issues and pull requests. Angular plugin for linechart also exists. Check angular-scale if you're using Angular.js.

alt text

Inspired by kinopoisk.ru chart written using Adobe Flash. But this chart is just on HTML/CSS without using libraries. Feel free for contribute.

alt text

Install

bower install jquery-linechart 
npm install jquery-linechart

Use

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <link rel="stylesheet" type="text/css" href="../scale.css">
    </head>
    <body>
        <div id="chart"></div>

        <script src="http://code.jquery.com/jquery-3.1.1.min.js" integrity="sha256-hVVnYaiADRTO2PzUGmuLJr8BLUSjGIZsDYGmIJLv2b8=" crossorigin="anonymous"></script>
        <script src="../scale.js"></script>
    </body>
</html>
$.getJSON('./votes.json', function(res) {
    var items = [];

    $.each(res, function(key, val){
        items.push({
            value: val["rank"],
            title: val["title"]
        });
    });

    $("#chart").linechart({
        data: items,
        width: 50, 
        height: 10,
        boxSize: 16,
        line: true,
        theme: "purple"
    });
});

Options

$("#chart").linechart({
    data: items,
    width: 50, 
    height: 10,
    boxSize: 16,
    line: true,
    theme: "purple"
});
  • data is an array of objects [{value: 0}, ... , {value: 10}]. This is the dataset of the chart.
  • width is the horizontal length of the data array. If width param is less than the length of the data array then user will see the last values of the data array.
  • height is the vertical length.
  • box-size is size of each box in pixels.

alt text

  • line is param that determines if this is a line-chart.

alt text

  • theme is color scheme of the chart.

alt text

Please check the example folder to see how it's going on practice.

Themes

  • default
  • purple
  • grey

alt text

Author: Kis
Source Code: https://github.com/kis/jquery-linechart
License: MIT license

#javascript #jquery #chart 

JQuery-linechart: JQuery Plugin for Creating Charts
Reid  Rohan

Reid Rohan

1658319780

Scale: Angular Plugin for Creating Charts

Scale

Angular plugin for building scale of items. Chart ruler completely on HTML/CSS/JS. Bar chart, line chart, calendar view visualisation. Diagram, graph, pyramid visualisation of large datasets. Showreel. The source for this module is in the main repo. Please create issues and pull requests.

alt text

Inspired by kinopoisk.ru chart written using Adobe Flash. But this chart is just on HTML/CSS without using libraries. Feel free for contribute.

alt text

Install

bower install angular-scale 
npm install angular-scale 

Use

<!DOCTYPE html>
<html ng-app="myApp">
    <head>
        <meta charset="utf-8">
        <link rel="stylesheet" type="text/css" href="../scale.css">
    </head>
    <body ng-controller="main">
        <scale data="data" 
               width="50" 
               height="10"
               box-size="14"
               line="true"
               theme="default">
        </scale>

        <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.7/angular.min.js"></script>
        <script src="../scale.js"></script>
        <script src="./index.js"></script>
    </body>
</html>
angular.module('myApp', ['scale']).controller('main', ['$scope', function($scope) {
    $scope.data = [];

    var SCALE_WIDTH = 50,
        SCALE_HEIGHT = 10;

    for (var i=0; i < SCALE_WIDTH; i++) {
        var value = Math.floor(Math.random() * SCALE_HEIGHT + 1);

        $scope.data.push({
            value: value, //Value from 1 to SCALE_HEIGHT
            title: (i + 1) + " item" //Description
        });
    }
}]);

Options

<scale data="data" 
       width="50" 
       height="10"
       box-size="14"
       line="true"
       theme="default">
</scale>
  • data is an array of objects [{value: 0}, ... , {value: 10}]. This is the dataset of the chart.
  • width is the horizontal length of the data array. If width param is less than the length of the data array then user will see the last values of the data array.
  • height is the vertical length.
  • box-size is size of each box in pixels.

alt text

  • line is param that determines if this is a line-chart.

alt text

  • theme is color scheme of the chart.

alt text

Please check the example folder to see how it's going on practice.

Themes

  • default
  • purple
  • grey

alt text

Changelog

  • 10/02/2016 Implemented tooltips.
  • 10/01/2016 Implemented different color schemes.
  • 09/20/2016 Rewriting the project as an Angular.js plugin.
  • 06/05/2016 Finished writing function for calculating angle of the line that connects the points of the chart. Rendering chart.

Author: Kis
Source Code: https://github.com/kis/scale 
License: MIT license

#javascript #chart #timeline #angular 

Scale: Angular Plugin for Creating Charts
Reid  Rohan

Reid Rohan

1658304660

Smooooooth JavaScript Charts for Realtime Streaming Data

Smoothie Charts is a really small charting library designed for live streaming data. I built it to reduce the headaches I was getting from watching charts jerkily updating every second.


Example

Given a <canvas>:

<canvas id="chart" width="400" height="100"></canvas>

Create a time series and chart with code resembling:

// Create a time series
var series = new TimeSeries();

// Find the canvas
var canvas = document.getElementById('chart');

// Create the chart
var chart = new SmoothieChart();
chart.addTimeSeries(series, { strokeStyle: 'rgba(0, 255, 0, 1)' });
chart.streamTo(canvas, 500);

Then, add data to your time series and it will be displayed on the chart:

// Randomly add a data point every 500ms
setInterval(function() {
    series.append(Date.now(), Math.random() * 10000);
}, 500);

Questions

For help, use the Smoothie Charts Google Group.


Getting Started


See http://smoothiecharts.org


Author: joewalnes
Source Code: https://github.com/joewalnes/smoothie 
License: View license

#javascript #chart #streaming 

Smooooooth JavaScript Charts for Realtime Streaming Data
Rocio  O'Keefe

Rocio O'Keefe

1658194620

Flutter_pie_chart: A Flutter Package for Pie Chart

A Flutter package for cool design and animation of Pie Chart.

Features

Screenshot 2021-11-29 120133 Screenshot 2021-11-29 120200 Screenshot 2021-11-29 120101

https://user-images.githubusercontent.com/75254562/143841160-91717ca9-95b6-4f0e-8de4-4b796ca6c62c.mp4

Usage

TODO: Include short and useful examples for package users. Add longer examples to /example folder.

Pie class exapmle:

final List<Pie> pies = [
    Pie(color: const Color(0xFFFF6262), proportion: 8),
    Pie(color: const Color(0xFFFF9494), proportion: 3),
    Pie(color: const Color(0xFFFFDCDC), proportion: 8),
  ];

Flutter pie widget example. The selected pie must be in the range of the pies list.

    FlutterPieChart(
      pies: pies,
      selected: 2,
    ),

Installing

Use this package as a library

Depend on it

Run this command:

With Flutter:

 $ flutter pub add flutter_pie_chart

This will add a line like this to your package's pubspec.yaml (and run an implicit flutter pub get):

dependencies:
  flutter_pie_chart: ^0.0.1

Alternatively, your editor might support flutter pub get. Check the docs for your editor to learn more.

Import it

Now in your Dart code, you can use:

import 'package:flutter_pie_chart/flutter_pie_chart.dart';

example/lib/main.dart

import 'package:flutter/material.dart';
import 'package:flutter_pie_chart/flutter_pie_chart.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter pie chart example',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: const MyHomePage(),
      debugShowCheckedModeBanner: false,
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({
    Key? key,
  }) : super(key: key);

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  final List<Pie> pies = [
    Pie(color: const Color(0xFFFF6262), proportion: 8),
    Pie(color: const Color(0xFFFF9494), proportion: 3),
    Pie(color: const Color(0xFFFFDCDC), proportion: 8),
  ];
  @override
  Widget build(BuildContext context) {
    final deviceSize = MediaQuery.of(context).size;
    return Scaffold(
      appBar: AppBar(
        title: const Text('Flutter pie chart'),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            SizedBox(
              width: deviceSize.width * 0.5,
              child: Padding(
                padding: const EdgeInsets.all(8.0),
                child: FlutterPieChart(
                  pies: pies,
                  selected: 2,
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }
}

Original article source at: https://pub.dev/packages/flutter_pie_chart 

#flutter #chart #dart 

Flutter_pie_chart: A Flutter Package for Pie Chart