Skip to main content
Version: 1.0.0

Introduction to Text Layer

What is a text layer?

A layer with mark text draws text. Muze by default does not show any annotations (text) on a plot. If you need text labels on charts, you have to add this layer along with the encoding.

Example

const { muze, getDataFromSearchQuery } = viz;

const data = getDataFromSearchQuery();

muze
.canvas()
.rows(["Displacement"])
.columns(["Horsepower"])
.detail(["Name"])
.layers([
{
mark: "text",
encoding: {
text: "Displacement",
},
},
])
.data(data)
.mount("#chart");

Creating a bar chart with labels using text layer

Let us see how to add a text layer to a bar chart. These text will show the value of the bars.

Example

const { muze, getDataFromSearchQuery } = viz;

const data = getDataFromSearchQuery();

muze
.canvas()
.rows(["Miles_per_Gallon"])
.columns(["Origin"])
.layers([
{
mark: "bar",
},
{
mark: "text",
encoding: {
text: {
field: "Miles_per_Gallon",
formatter: (v) => Math.round(v.rawValue),
},
color: {
value: () => "#000",
},
y: {
value: (d) => d.translatedValue - 15,
},
},
},
])
.data(data)
.mount("#chart");

NOTE: text encoding tells the text layer which field's value it has to display. The formatter function returns a formatted value which will be shown in the chart. The color.value function sets a different color to the labels and using value function in y encoding we adjust the y position of the text so that it does not overlaps with the bars.

Creating a pie chart with labels using text layer

For a pie chart with labels, we follow the similar steps as above, and also add an angle to the text layer, so that it is placed properly in accordance with the pie.

Example

const { muze, getDataFromSearchQuery } = viz;

const data = getDataFromSearchQuery();
let dm = new DataModel(data);

const dmWithCount = dm.calculateVariable(
{
name: "countVehicle",
type: "measure",
defAggFn: "count",
format: (val) => parseInt(val, 10),
},
["Name"],
() => 1
);

muze
.canvas()
.rows([])
.columns([])
.color("Origin")
.layers([
{
mark: "arc",
encoding: {
angle: "countVehicle",
},
},
{
mark: "text",
encoding: {
angle: "countVehicle",
text: {
field: "countVehicle",
},
color: {
value: () => "#000",
},
x: {
value: (d) => {
if (d.datumIdx == 0) {
return d.translatedValue + 100;
}
if (d.datumIdx == 1) {
return d.translatedValue - 100;
}
if (d.datumIdx == 2) {
return d.translatedValue - 80;
}
},
},
y: {
value: (d) => {
if (d.datumIdx == 0 || d.datumIdx == 1) {
return d.translatedValue + 20;
}
if (d.datumIdx == 2) {
return d.translatedValue - 100;
}
},
},
},
},
])
.title("Pie Chart", { position: "top", align: "center" })
.subtitle("Count of cars for each Origin", {
position: "top",
align: "center",
})
.data(dmWithCount)
.width(500)
.height(600)
.mount("#chart");