Skip to main content
Version: Current

Creating crosstab

What is a crosstab?

Crosstab is a simple table where instead of numbers in table cells, a bar is shown. The length of the bar is proportional to the value of the cell.

Creating a simple crosstab (bar)

Crosstab for Acceleration and Horsepower of Cars for each Cylinder faceted by Origin.

Example

const { muze, getDataFromSearchQuery } = viz;

const data = getDataFromSearchQuery();

muze
.canvas()
.rows(["Acceleration", "Horsepower"])
.columns(["Origin", "Maker"])
.data(data)
.width(800)
.height(700)
.mount("#chart");

Changing configurations

Adding fields/measures

Adding a field is as easy as adding it in the rows/columns passed to Muze.

In the first crosstab, adding a measure field (Weight_in_lbs), gives us the following:

Example

const { muze, getDataFromSearchQuery } = viz;

const data = getDataFromSearchQuery();

muze
.canvas()
.rows(["Acceleration", "Horsepower", "Weight_in_lbs"])
.columns(["Year", "Origin"])
.layers([
{
mark: "bar",
},
])
.data(data)
.width(700)
.height(700)
.mount("#chart");

Changing orientation (x vs y)

To alter the x/y axes of the chart, simply invert the fields passed to rows and columns.

Taking the previous chart and swapping the rows and columns, you get:

Example

const { muze, getDataFromSearchQuery } = viz;

const data = getDataFromSearchQuery();

muze
.canvas()
.rows(["Year", "Origin"])
.columns(["Acceleration", "Horsepower", "Weight_in_lbs"])
.layers([
{
mark: "bar",
},
])
.data(data)
.width(700)
.height(700)
.mount("#chart");

Creating a crosstab of pie charts

Creating a crosstab and specifying the mark type as arc produces a crosstab of pie charts. The color field then is applied to each pie to create multiple slices of the pie.

Example

const { muze, getDataFromSearchQuery } = viz;

const data = getDataFromSearchQuery();

let dm = new DataModel(data);

dm = dm.select({
operator: "and",
conditions: [
{
field: "Year",
value: "1970-01-01",
operator: "gt",
},
{
field: "Year",
value: "1980-01-01",
operator: "lte",
},
{
field: "Origin",
value: ["USA", "Japan"],
operator: "in",
},
{
field: "Cylinders",
value: ["4", "6"],
operator: "in",
},
],
});

muze
.canvas()
.rows([["Year", "Origin"]])
.columns(["Cylinders"])
.layers([
{
mark: "arc",
encoding: {
color: "Maker",
text: "Maker",
angle: "Horsepower",
radius: "Horsepower",
},
},
])
.config({
gridLines: {
x: {
show: false,
},
y: {
show: false,
},
},
axes: {
x: {
tickInterval: {
step: "year",
},
},
},
uniformAxisDomains: false,
})
.title("Cross-tab Pie Chart", { position: "top", align: "center" })
.data(dm)
.width(900)
.height(800)
.mount("#chart");