Multiple bars in a single plot #1032
-
Hello! I want to display multiple bars in a single plot. I cannot find anything related in the docs, and also no example for that. using this code: Plot.plot({
marks: [
Plot.barX(data, {
y: 'stat',
x: 'old',
fill: '#4e79a7',
}),
Plot.barX(data, {
y: 'stat',
x: 'new',
height: 5,
fill: '#cc5555',
dy: 10,
}),
],
x: {grid: true, label: 'Time (seconds)'},
y: {grid: true, label: 'Metric'},
}); How can I plot multiple bars, or just adjust the width/height of the bars?
|
Beta Was this translation helpful? Give feedback.
Replies: 4 comments 12 replies
-
I think you could use |
Beta Was this translation helpful? Give feedback.
-
I recommend using faceting for this, and using a “tidy” representation of data where there is one row per observation, rather than treating the “new” and “old” observations as separate dimensions. To tidy the data, you could say: tidy = data.flatMap((d) => [
{ stat: d.stat, series: "old", time: d.old },
{ stat: d.stat, series: "new", time: d.new }
]) Then to use faceting, you could say: Plot.plot({
x: { grid: true, label: "Time (seconds)" },
y: { label: "Metric", axis: null },
color: { legend: true },
facet: {
data: tidy,
y: "stat",
marginLeft: 60
},
marks: [
Plot.barX(tidy, {
x: "time",
y: "series",
fill: "series"
})
]
}) Live notebook: https://observablehq.com/d/47d887315e24c39b |
Beta Was this translation helpful? Give feedback.
-
Another approach would be to make the “new” values more prominent (i.e., you want to see the new values in the context of the old values), and then show the change with a link or arrow. Plot.plot({
x: { grid: true, label: "Time (seconds)" },
y: { label: "Metric" },
marks: [
Plot.barX(data, { x: "new", y: "stat", fill: "#ccc" }),
Plot.ruleX([0]),
Plot.tickX(data, { x: "new", y: "stat", strokeWidth: 1.5 }),
Plot.arrow(data, { x1: "old", x2: "new", y: "stat", stroke: "red" }),
Plot.dot(data, { x: "old", y: "stat", fill: "red" })
]
}) Shown here: https://observablehq.com/d/47d887315e24c39b |
Beta Was this translation helpful? Give feedback.
-
@PatrickBuTaxdoo As pointed out above you could use inset to overlay the bars too like this (needs tweaking probably): https://observablehq.com/d/20c995d04b71e4db#cell-8 I'm not sure why the legend isn't displaying though. Margin/padding needs adding? |
Beta Was this translation helpful? Give feedback.
I recommend using faceting for this, and using a “tidy” representation of data where there is one row per observation, rather than treating the “new” and “old” observations as separate dimensions. To tidy the data, you could say:
Then to use faceting, you could say:
Live note…