Giter Site home page Giter Site logo

vue-chartkick's Introduction

Vue Chartkick

Create beautiful JavaScript charts with one line of Vue

See it in action

Supports Chart.js, Google Charts, and Highcharts

Build Status

Quick Start

Run

npm install vue-chartkick chart.js

The latest version works with Vue 3. For Vue 2, use version 0.6.1 and this readme.

And add it to your app

import VueChartkick from 'vue-chartkick'
import 'chartkick/chart.js'

app.use(VueChartkick)

This sets up Chartkick with Chart.js. For other charting libraries, see detailed instructions.

Charts

Line chart

<line-chart :data="{'2021-01-01': 11, '2021-01-02': 6}"></line-chart>

Pie chart

<pie-chart :data="[['Blueberry', 44], ['Strawberry', 23]]"></pie-chart>

Column chart

<column-chart :data="[['Sun', 32], ['Mon', 46], ['Tue', 28]]"></column-chart>

Bar chart

<bar-chart :data="[['Work', 32], ['Play', 1492]]"></bar-chart>

Area chart

<area-chart :data="{'2021-01-01': 11, '2021-01-02': 6}"></area-chart>

Scatter chart

<scatter-chart :data="[[174.0, 80.0], [176.5, 82.3]]" xtitle="Size" ytitle="Population"></scatter-chart>

Geo chart - Google Charts

<geo-chart :data="[['United States', 44], ['Germany', 23], ['Brazil', 22]]"></geo-chart>

Timeline - Google Charts

<timeline :data="[['Washington', '1789-04-29', '1797-03-03'], ['Adams', '1797-03-03', '1801-03-03']]"></timeline>

Multiple series

data = [
  {name: 'Workout', data: {'2021-01-01': 3, '2021-01-02': 4}},
  {name: 'Call parents', data: {'2021-01-01': 5, '2021-01-02': 3}}
];

and

<line-chart :data="data"></line-chart>

Data

Data can be an array, object, callback, or URL.

Array

<line-chart :data="[['2021-01-01', 2], ['2021-01-02', 3]]"></line-chart>

Object

<line-chart :data="{'2021-01-01': 2, '2021-01-02': 3}"></line-chart>

Callback

function fetchData(success, fail) {
  success({"2021-01-01": 2, "2021-01-02": 3})
  // or fail("Data not available")
}

and

<line-chart :data="fetchData"></line-chart>

URL

Make your pages load super fast and stop worrying about timeouts. Give each chart its own endpoint.

<line-chart data="/stocks"></line-chart>

Options

Id, width, and height

<line-chart id="users-chart" width="800px" height="500px"></line-chart>

Min and max values

<line-chart :min="1000" :max="5000"></line-chart>

min defaults to 0 for charts with non-negative values. Use null to let the charting library decide.

Min and max for x-axis - Chart.js

<line-chart xmin="2021-01-01" xmax="2022-01-01"></line-chart>

Colors

<line-chart :colors="['#b00', '#666']"></line-chart>

Stacked columns or bars

<column-chart :stacked="true"></column-chart>

Discrete axis

<line-chart :discrete="true"></line-chart>

Label (for single series)

<line-chart label="Value"></line-chart>

Axis titles

<line-chart xtitle="Time" ytitle="Population"></line-chart>

Straight lines between points instead of a curve

<line-chart :curve="false"></line-chart>

Show or hide legend

<line-chart :legend="true"></line-chart>

Specify legend position

<line-chart legend="bottom"></line-chart>

Donut chart

<pie-chart :donut="true"></pie-chart>

Prefix, useful for currency - Chart.js, Highcharts

<line-chart prefix="$"></line-chart>

Suffix, useful for percentages - Chart.js, Highcharts

<line-chart suffix="%"></line-chart>

Set a thousands separator - Chart.js, Highcharts

<line-chart thousands=","></line-chart>

Set a decimal separator - Chart.js, Highcharts

<line-chart decimal=","></line-chart>

Set significant digits - Chart.js, Highcharts

<line-chart :precision="3"></line-chart>

Set rounding - Chart.js, Highcharts

<line-chart :round="2"></line-chart>

Show insignificant zeros, useful for currency - Chart.js, Highcharts

<line-chart :round="2" :zeros="true"></line-chart>

Friendly byte sizes - Chart.js 2.8+

<line-chart :bytes="true"></line-chart>

Specify the message when the chart is loading

<line-chart loading="Loading..."></line-chart>

Specify the message when data is empty

<line-chart empty="No data"></line-chart>

Refresh data from a remote source every n seconds

<line-chart :refresh="60"></line-chart>

You can pass options directly to the charting library with:

<line-chart :library="{backgroundColor: '#eee'}"></line-chart>

See the documentation for Google Charts, Highcharts, and Chart.js for more info.

To customize datasets in Chart.js, use:

<line-chart :dataset="{borderWidth: 10}"></line-chart>

You can pass this option to individual series as well.

Use dynamic components to make the chart type dynamic:

<component is="column-chart"></component>

Reactivity

While some of the examples use object or array literals in props for demonstration, this can lead to unnecessary re-renders.

<line-chart :library="{backgroundColor: '#eee'}"></line-chart>

Instead, use a data property:

<line-chart :library="library"></line-chart>

See this discussion for more details.

Global Options

To set options for all of your charts, use:

Chartkick.options = {
  colors: ["#b00", "#666"]
}

Multiple Series

You can pass a few options with a series:

  • name
  • data
  • color
  • dataset - Chart.js only
  • points - Chart.js only
  • curve - Chart.js only

Download Charts

Chart.js only

Give users the ability to download charts. It all happens in the browser - no server-side code needed.

<line-chart :download="true"></line-chart>

Set the filename

<line-chart download="boom"></line-chart>

Note: Safari will open the image in a new window instead of downloading.

Set the background color

<line-chart :download="{background: '#fff'}"></line-chart>

Installation

Chart.js

Run

npm install vue-chartkick chart.js

And add

import VueChartkick from 'vue-chartkick'
import 'chartkick/chart.js'

app.use(VueChartkick)

Google Charts

Run

npm install vue-chartkick

And add

import VueChartkick from 'vue-chartkick'

app.use(VueChartkick)

And include on the page

<script src="https://www.gstatic.com/charts/loader.js"></script>

To specify a language or Google Maps API key, use:

Chartkick.configure({language: "de", mapsApiKey: "..."})

Highcharts

Run

npm install vue-chartkick highcharts

And add

import VueChartkick from 'vue-chartkick'
import 'chartkick/highcharts'

app.use(VueChartkick)

No Package Manager

Include the charting library and the Chartkick library

<script src="https://unpkg.com/[email protected]/dist/chart.umd.js"></script>
<script src="https://unpkg.com/[email protected]/dist/chartjs-adapter-date-fns.bundle.js"></script>
<script src="https://unpkg.com/[email protected]"></script>
<script src="https://unpkg.com/[email protected]"></script>

And add

app.use(VueChartkick)

Multiple Libraries

If more than one charting library is loaded, choose between them with:

<line-chart adapter="google"></line-chart>

Options are google, highcharts, and chartjs

Example

<div id="app">
  <line-chart :data="chartData"></line-chart>
</div>

<script>
  var app = Vue.createApp({
    el: "#app",
    data: {
      chartData: [["Jan", 4], ["Feb", 2], ["Mar", 10], ["Apr", 5], ["May", 3]]
    }
  })
  app.use(VueChartkick)
  app.mount("#app")
</script>

History

View the changelog

Contributing

Everyone is encouraged to help improve this project. Here are a few ways you can help:

To get started with development, run:

git clone https://github.com/ankane/vue-chartkick.git
cd vue-chartkick
npm install
npm run build

vue-chartkick's People

Contributors

ankane avatar e200 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

vue-chartkick's Issues

Error: No element with id users-chart

I follow the setup guidance & add the following line into my html file:
<line-chart id="users-chart" width="800px" height="500px"></line-chart>

However, when starting up, it says the error
Error: No element with id users-chart

After for a while of researching, I still can't solve it T.T

Can you give me any idea?

column-chart multi columns

Hello Ankane.
I don't find how to set data to display columns with 2 or more sub-columns per column.
For exemple incomes/outcomes per month.

In googles charts the data are :
var data = google.visualization.arrayToDataTable([
['Year', 'Sales', 'Expenses', 'Profit'],
['2014', 1000, 400, 200],
['2015', 1170, 460, 250],
['2016', 660, 1120, 300],
['2017', 1030, 540, 350]
]);
It would be great if you could tell me and usefull also for others.
Thank you.
Joannes

Geo Charts - States within one country

Brilliant library!
Got a question, how do I display the states within a country?

I've got the ISO codes list Google uses.

How do I tell <geo-chart ... > which country to select?

I've already tried this:

<geo-chart :data="[['MY-14', 44], ['MY-12', 23], ['MY-10', 22]]"></geo-chart>

Which doesn't work.

Thanks in advance.

How do you change the width of the line in a line chart

Hi,

I've been asked to make the line in a line chart thicker, and for the life of me I can't work out where I need to put the borderWidth property to get it be picked up by the component. It seems I need to ideally add it to a 'custom' array in the dataset but I can't get the syntax right. Can you advise the right config to pass please?

Thanks in advance for your help!

Since the recent update, my charts on other tabs don't display.

I'm using elements-ui to create a series of tabs, using a prior release- charts on non-visible tabs, showed up fine when the tab was selected. Did an upgrade a few days back.

I'm using Charts.js.

The recent update broke something. The first tab shows the charts fine. Selecting other tabs, the charts don't show.
First tab:
image

Second tab (no hot deploy changes yet):
image

After hot deploy changes (just changed something trivial like the thousands separator):
image

Using yarn run dev if I change something like :donut="false" to :donut="true" in the code, then the chart shows. Some kind of refresh issue perhaps?

Error parsing date

Hello,
I am displaying data behavior through time, i have the dates on Y-m-d format, when i pass the dates like that, for example 2017-08-09 it works well, but i have data aggregated by month, but i dont want the data from month 2017-08 to accumulate with 2016-08. i tried to pass the dates on format Y-m but it parses it incorrectly. for example, i tried passing 2017-08 and it converts it on july 31 7:00 pm. 'visits' is the data that i am passing
image

hope you can help

Wait until google chart loads

I think you need to wait until the google chart script loads before initializing the chart. Because I get No adapter found on refresh or first load.

Loading options...

Time permitting, can you add the ability to override the loading indicator? Currently it just flashes a very unstyled bit of text, "Loading...", which doesn't look great. I'd love to either be able to remove it completely (because it happens so quickly and can be jarring), or perhaps allow HTML to be provided so that the user can style it to their liking.

image

Error Loading Chart: Cannot read property 'length' of undefined on :message="{empty: 'No data'}"

I have this template.

<pie-chart  :messages="{empty: 'No data'}" :legend="false" :donut="true" :data="chartData"/>

I change chartData dynamically by letting the user select a date and calling my backend for the data. Everything's fine until you do these steps:

  1. chartData is null, No data is displayed.
  2. chartData is not null (choose a date with data)
  3. chartData is null, No data is displayed
  4. chartData is not null.

Expected: Data is displayed.
Actual: Error Loading Chart: Cannot read property 'length' of undefined

Having this stacktrace:

TypeError: Cannot read property 'length' of undefined
    at Object.acquireContext (platform.dom.js?0cdd:340)
    at Chart.construct (core.controller.js?821b:79)
    at new Chart (core.js?f88b:42)
    at drawChart (chartjs.js?949b:124)
    at Object.renderPieChart (chartjs.js?949b:435)
    at callAdapter (chartkick.js?f20b:175)
    at renderChart (chartkick.js?f20b:155)
    at PieChart.__render (chartkick.js?f20b:403)
    at errorCatcher (chartkick.js?f20b:36)
    at fetchDataSource (chartkick.js?f20b:53)

I have investigated and I think the problem is in this code:

let drawChart = function(chart, type, data, options) {
  if (chart.chart) {
    chart.chart.destroy();
  } else {
    chart.element.innerHTML = "<canvas></canvas>";
  }

On step 2, chart.chart is undefined. It then creates "<canvas></canvas>" everything goes smoothly.
The problem is on step 3. chart.chart is not cleared or something so when step 4 comes in, if (chart.chart) returns true. Then the call to chart.js:

line 123: let ctx = chart.element.getElementsByTagName("CANVAS")[0];

returns null. and The chart constructor needs that to build new one. This thing on platform.dom.js fails:

line 340: acquireContext: function(item, config) {
		if (typeof item === 'string') {
			item = document.getElementById(item);
		} else if (item.length) {
			// Support for array based queries (such as jQuery)
			item = item[0];
		}

I tested just tested it with the following scenario too

  1. chartData is not null
  2. chartData is not null
    chart.chart is destroyed, so everything fails again.

This only happens when I have that messages prop.
I'm using Google Chrome Version 63.0.3239.132

I think this is quite an easy fix, perhaps just always create the canvas on drawChart()

let drawChart = function(chart, type, data, options) {
  if (chart.chart) {
    chart.chart.destroy();
  }
  chart.element.innerHTML = "<canvas></canvas>";

Or Idk. There might be a reason behind this.

PS: Sorry for the long post, this was my first issue submission. Has always been on the sideline. I've always wanted to participate in the open source community. Just didn't have the confidence if I actually can.

Chartkick is undefined after update

console logs Chartkick is undefined after update

"chartkick": "^2.3.5",
"vue-chartkick": "^0.2.2",
import Vue from 'vue'
import VueChartkick from 'vue-chartkick'
import Chart from 'chart.js'

Vue.use(VueChartkick, {adapter: Chart})

The 'dataset' options have no effect

Using the following minimal example

<line-chart :dataset="{borderWidth: 10}" :data="{'A': 44, 'B': 23, 'C': 60, 'D': 50}"></line-chart>

the boarderWidth parameter does not change the line width, no matter what number is used.

Is there a way to hide x-axis and y-asix

Hi,

I am wondering if there is a way to hide the axises, and leave the chart itself only.

I check the document and didn't find a way to hide it, any guides or tips are welcome. Thanks in advance

Support for multiple axis?

Here are some options I was using with Google Charts before I converted my site to VueJS. I haven't been able to figure out to use them with this library yet, is it possible?

This is from a combo chart, but I'm fine with using line-chart in this library if I can get my second axis to be different from the first

options = {


           seriesType: 'bars',    
 
            series: {

              1: {side: 'right', type: "line", targetAxisIndex:1}, // Right y-axis.
              2: {targetAxisIndex:0},
            },
            
              axes: {
            y: {
      				
              1: {side: 'right'} // Right y-axis.
            }
          },

          colors: ["lightblue", "green"],};     

How can i pass parameter of the native api

I'm trying to change the background color of my graph but i don't know how. I tried

<pie-chart :options="options" :data=percentual()></pie-chart>

      options: {
        backgroundColor: '#eee'
      }

but it not works

line charts with null value

Hi, im using this awesome lib and i got a issue when im trying to show a line charts with a null value. when the charts is rendered the line chart is cut. But, using Chartjs the chart is rendered without problem. Its possible to render the line chart with theese values?

 prueba : [
    {name: 'prueba', data:{"Jan":12,"test":null,"Mar":23,"Abr":2,"Jun":55,"Jul":null,"Ago":123,"Sept":23,"Oct":1,"Nov":5,"Dic":53}}       
   ]

Here a screenshot with the result of rendered chart

sin titulo

[BarChart] Properties library

Hi, thanks for the wonderful plugins. Here, I'm trying to override some properties using library, sample code below:

<bar-chart 
  :data="[['Unknown', 300], ['Receiver', 500], ['Voters', 1000]]"
  :colors="['#209cee', '#01d1b2', '#ffde56']"
  :library="{'borderWidth': 0}" 
  :height="160"
  :legend="false" />

Seems like this particular chart can't pickup properties override for library/colors. Can someone point me to correct implementation, perhaps I've missed it from docs. Thanks

is there a way to change axis language?

Thank you for your work.

I've encountered a problem. Dates are converted in English month names automatically. Is there a way to change axis labels' language? Or maybe I can prevent this date-to-month-name convertion somehow?

Cannot read property 'LineChart' of undefined

Hello,

I've installed chartkick, vue-chartkick & chart.js like so:

npm i -S chartkick vue-chartkick chart.js

Then I have imported it:

import Chartkick from 'chartkick'
import VueChartkick from 'vue-chartkick'
import Chart from 'chart.js'

Vue.use(VueChartkick, { Chartkick });

But now nothing renders anymore, and I have this message in my console:
"Uncaught TypeError: Cannot read property 'LineChart' of undefined
at Object.install (webpack-internal:///./node_modules/vue-chartkick/index.js:80)
at Function.Vue.use (webpack-internal:///./node_modules/vue/dist/vue.esm.js:4615)
at eval (webpack-internal:///./src/main.js:28)
at Object../src/main.js (app.js:2705)
at webpack_require (app.js:679)
at fn (app.js:89)
at Object.0 (app.js:2722)
at webpack_require (app.js:679)
at app.js:725
at app.js:728"

Thank you for your time! :)

RESOLVED Can you give a webpack example?

Hi sorry for newb question but your example only shows for a simple vue instance, but I am using webpack simple boilerplate and I cant get it to work. I think I need to import the component?

'[Vue warn]: Failed to mount component: template or render function not defined.'


<script>
import Chartkick from 'chartkick'
import VueChartkick from 'vue-chartkick'
import Chart from 'chart.js'
Vue.use(VueChartkick, { Chartkick })

import axios from 'axios';


export default {

  name: 'analytics',
  data: () => ({
   chartData: [["Jan", 4], ["Feb", 2], ["Mar", 10], ["Apr", 5], ["May", 3]]


  })
}
</script>

Feature request: emit events

Hi,

I gave vue-chartkick a spin the last couple of days and so far it works great. However, what really would be a great feature for me is that when you click any of the chart parts it would emit an event. In that way you can also easily build charts that respond on clicks (for example, add a filter on a certain part of the data when you click that piece of the pie). Thanks for this module!

Cheers

How to change color tooltip in pie-chart

I don't know why my tooltip font color is gray.

I try add config follow document like this.

Chart.defaults.global.tooltips.titleFontColor = "#fff";
Chart.defaults.global.tooltips.bodyFontColor = "#fff";
Chart.defaults.global.tooltips.footerFontColor = "#fff";
Chart.defaults.global.tooltips.multiKeyBackground = "#fff";

But it not working

2017-10-01_131505

Responsive charts

Hello,
how can I make my chartjs charts responsive?

I have problems both with window resize and in the print mode..

Thanks

Redraw on data update

I have data that can be updated, how I redraw the chart? I'm using Google Charts..

Render Geo Chart on state change

Hello.
Love this package.
It works really well with a line chart.
When I try using a geo chart which the data come from vuex state.
It wont update when the state changes?

I have a watch that watches a drop down

  watch: {
    product: function(product) {
      this.getProductByCountry(product);
    },
  },

and a computed which maps the state

  computed: {
    ...mapState({
      productbycountry: state => state.analytics.productsbycountry,
    }),
  },

and this is my geo chart
<geo-chart :data="productbycountry" id="geo"></geo-chart>
When I change the product, the geo chart does not update.

It works with the line chart.

Any ideas on how I can get my geo-chart to update when i can the product?

Much Appreciated

Line chart not using library prop

I've added a library prop e.g.:
<line-chart :data="..." :library="{ steppedLine: true }"></line-chart>

Yet the options aren't reflected in the chart. I'm using a line chart. After looking at the dist files it seems the library options aren't merged? Whereas other charts merge the library options.

multiple call of updated for each change in the dom leads to worse animation

Hi,
first vue-chartkick and chartkick itself is awesome an I like to use it.

I recently discovered some not so nice effect. The charts were updated for each single change in the actual page. That means if you use animation than you will discover that i.e. a pie chart is painted multiple times each time a little bit more. That looks ugly. The reason for this is, that a chart is painted in the method updated and not using a watch on the data. I thinks that would be the right implementation.

Kind regards
Dirk

library options (again)

hi there

I really can't set some options here:

doesn't work. I've already tried

<area-chart :data="heatMap" :stacked="true" :discrete="true" :library="{

chart: {backgroundColor: {
linearGradient: [0, 0, 500, 500],
stops: [
[0, 'rgb(255, 255, 255)'],
[1, 'rgb(240, 240, 255)']
]
}}
}" >

Also, is it possible to hide the dot ? I'm creating a heatmap. All I need is gradient.

How set google column-chart to matherial theme?

Hello. i need change google column-chart classic theme , to google material desing
How i can do this? i try use :library="{theme: 'material}" but there dont change.
In google docs theme may change in initialization var data = google.visualization.arrayToDataTable([

Properties

Where can we see the full list of properties we can use?
I'm using line-chart and what I understand that belongs to Chart.js and I'm trying to use the property pointRadius so I can see big chunks of data without points only a line.
I've tried
-> line-chart :pointRadius="0" :options="myOptions"
-> inside the options
-> using the property dataset

But none of those work.
Can you give a some some help pls?

how library props works?

<bar-chart 
            :library="{backgroundColor: '#63ffde'}"
            :height="'100px'"
            :download="true"
            :data="barData"></bar-chart>

I am using chart js and wanted to pass options directly to the charting library. As only the backgroundColor is not working, can you please tell me what am I doing wrong here?

Add "points" property so line-chart can be without points

Could you please add a "points" property, so the line-chart can be rendered without the line points.

var chartId = 1

var createComponent = function(Vue, tagName, chartType) {
var chartProps = [
"colors", "curve", "discrete", "donut", "download", "label",
"legend", "library", "max", "min", "points", "refresh",
"stacked", "title", "xtitle", "xtype", "ytitle", "points"
]
Vue.component(tagName, {
props: ["data", "id", "width", "height"].concat(chartProps),
render: function(createElement) {
return createElement(
"div",
{
attrs: {
id: this.chartId
},
style: this.chartStyle
},
["Loading..."]
);
},

changes inside library property does not update the chart

Changes inside the library property does not trigger the update function for the chart because we shallow copy the properties in currentState and library is an object.

A workaround for this is to replace the complete object.

Example

does not work:
this.options.scales.yAxes[0].type = (this.options.scales.yAxes[0].type === 'linear') ? 'logarithmic' : 'linear'

this works:
this.options = {...this.options, scales: { yAxes: [{type: ((this.options.scales.yAxes[0].type === 'linear') ? 'logarithmic' : 'linear')}]}}

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.