Struggling to make a chart responsive

My goal is to have a barY chart scale down in height up to a certain point (eg. 500px) and then keep that as the min-height while allowing to further scale down in width.

This basically allows a chart to go from “wide” to “tall” which should make it better readable on mobile devices.

Is there a way to set min-height in Plot that I have overlooked?

I’ve been playing around for hours with this example but can’t replicate the behavior (getting a JS error about missing width) and the absolute / relative positioning isn’t working for me either.

1 Like

The Credit link on the example you refer to points to this notebook, which is quite old. I’d recommend taking a look at the Bar Mark documentation, which generates the same example using Plot with the following code:

Plot.plot({
  x: {
    domain: d3.sort(alphabet, (d) => -d.frequency).map((d) => d.letter)
  },
  y: {
    grid: true
  },
  marks: [Plot.barY(alphabet, { x: "letter", y: "frequency" }), Plot.ruleY([0])]
})

Thanks @mcmcclur but I don’t think I was clear in my explanation.

What I’m looking for is a chart that scales when you resize the browser window. Yes, Plot does that by default. But the problem is that a chart can become very small in height. And what I’d like to have a min-height for a chart.

Update

Using Plot.plot({ width: Math.max(width, 550), … }) pretty much solved it for me. Found the solution over here.

Set the height field?

https://observablehq.com/d/741c7077b5ae6cc4

Just setting a fixed height isn’t going to cut it. You want a starting height, and every chart has that by default anyway. But from there the height will scale down proportionally. So when you have a “wide” chart that might look fine on a desktop on mobile it will be tiny and most likely unreadable. At some point you want the chart to have a min-height and only scale the width. Does that make sense?

The solution that I quoted above pretty much does the trick.

Sorry for the short response; I’m on my iPhone

Personally, I’d react to changes in width by swapping x and y. It’s hard to say for sure without seeing your notebook.

1 Like

Thanks, that’s an elegant solution as well in some cases!

When you have short and equal-length labels this works well (like in your chart) but it’s a challenge when labels are longer and different in length for instance country names.

Nevertheless, thanks for pointing this out and I didn’t realize that swapping axis could be done straight in Observable but makes sense.

1 Like