Custom Layer
Vue3-Charts is build to be highly customizable.
The library comes with some built-in layers (Line
, Bar
, Area
etc...) but you can easly write your own layers using the power of Vue3 composition api
Labels Layer
To demonstrate how to build a custom layer we will create a layer called Labels
The purpose of the layer is to display a label on the chart for each data point. Let's start with a simple line chart example.
As you can see in this example, it is very hard to see the values for each data point, so our layer will display a text with the value for each point.
To create our layer we will use the usePoints
hook provided by Vue3-Charts.
The hook will do all the job for us (mapping the data) and will give us a list of points that we can use to draw whatever we want, in our case we will simply draw a text.
Here is the code for our layer:
// LabelsLayer.vue <template> <g class="layer-labels"> <text v-for="(p, i) in points" :key="i" :x="p.x" :y="p.y - 10" text-anchor="middle" font-size="12" fill="#8884d8"> {{ p.props.data[dataKeys[1]] }} </text> </g> </template> <script lang="ts"> import { defineComponent } from 'vue' import { usePoints } from 'vue3-charts' export default defineComponent({ name: 'Labels', props: { dataKeys: { type: Object as () => [string, string], required: true } }, setup(props) { const { points } = usePoints(props.dataKeys) return { points } } }) </script>
And after we add this layer to our chart we get this result:
As you can see this is pretty easy and you can draw whatever you want. You can check the code for our built-in layers to learn more Line, Bar, Marker