Multiple bars side-by-side #1943
-
There are various posts and Notebooks relating to this issue, but I'm not sure what is the best / correct way of doing this. My data looks something like this:
I want this shown as a bar-plot with Date on the x-axis, Value on the y-axis, and the color according to Name. I would prefer the bars to be shown next to each other, rather than stacked on top of each other. I have tried the following:
The plot shows the bars stacked on top of each other, and I would prefer them side-by-side. When I have a lot of data-points the x-axis labels also look messy: I'm running this in a web-site and I get the following Java-script warning:
How can I show the bars side-by-side, and fix the x-axis labels? Thanks! |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 6 replies
-
Here's a way: Plot.rectY(data, {
x1: (d) => d3.utcHour.offset(d.Date, d.Name === "Bar" ? 8 : 0),
x2: (d) => d3.utcHour.offset(d.Date, d.Name === "Bar" ? 16 : 8),
y: "Value",
fill: "Name"
}) |
Beta Was this translation helpful? Give feedback.
-
Probably you want to use faceting here, along x by Date, so that you have side-by-side bars for each day. Plot.plot({
grid: true,
fx: {interval: "day"},
x: {axis: null, padding: 0},
y: {label: null},
color: {legend: true},
marks: [
Plot.barY(data, {fx: "Date", y: "Value", x: "Name", fill: "Name"}),
Plot.ruleY([0])
]
}) Notebook: https://observablehq.com/d/d7646ef51f9d78f2 Note that your fx scale should declare the expected time interval (above day) so that you get nice ticks. If you don’t specify the interval, Plot won’t be able to guess the time interval of your data, and won’t be able to reduce the number of ticks in some sensible manner to reduce overlap. For example, if you have five years of monthly data: data = d3.utcMonths(new Date("1962-01-01"), new Date("1967-01-01")).flatMap((Date) => ["cos", "sin"].map((f) => ({Date, Name: f, Value: Math[f](d3.utcDay.count(0, Date) / 100) + 2}))) You’ll get this if you change the fx interval to month: |
Beta Was this translation helpful? Give feedback.
Probably you want to use faceting here, along x by Date, so that you have side-by-side bars for each day.
Notebook: https://observablehq.com/d/d7646ef51f9d78f2
Note that your fx scale should declare the expected time interval (above day) so that you get nice ticks. If you don’t specify the interval, Plot won’t be able to guess the time interval of your data, and won’t be able to reduce the number of ticks in some sensible manner to reduce overlap.
For exa…