Issue
Problem
For example, I have data like this, where x is year and y is count:
{
"x": [1950, 2000, 2010],
"y": [1, 1, 5]
}
This means that the count is 1 between 1950-2000, also 1 between 2000-2010, and 5 between 2010-Now.
I want to make a histogram for this data. I feel that I'm very closed to the solution already, but somehow it still doesn't work.
What I have tried
I create a bar chart and set bargap to 0. Additionally, the width of each bar is the difference in the year. For example, the width of the first bar is 2000 - 1950 = 50. This is the function to calculate the bar width:
calculateBarWidth (data: PlotData) {
// The width of each bar is the difference between 2 consecutive years
const diff: number[] = []
for (let i = 1; i < data.x.length; i++) {
diff.push(data.x[i] - data.x[i - 1])
}
// Last diff
diff.push(10)
return diff
}
I also know that by default, Plotly puts the xtick in the middle of the bar. So, for the first bar at 1950, it will look like this, where 1950 is at the red line:
Since this is a histogram, I want the year to be at the beginning of the bar, so I set the bar offset to half of its width.
Putting everything together, this is my plot function:
createPlot (divElement: HTMLElement, data: PlotData) {
const barWidth = this.calculateBarWidth(data)
const barOffset = barWidth.map(value => value / 2)
const plotData: any = [{
x: data.x,
y: data.y,
type: 'bar',
width: barWidth,
offset: barOffset,
hovertext: this.createHoverText(data),
hoverinfo: 'text'
}]
const config = {
responsive: false,
displaylogo: false,
displayModeBar: false
}
const layout = {
title: {
text: this.title,
font: {
size: 14
}
},
xaxis: {
title: {
text: this.xlabel,
font: {
size: 14
}
},
tickfont: {
size: 12
}
},
yaxis: {
title: {
text: this.ylabel,
font: {
size: 14
}
},
tickfont: {
size: 12
}
},
bargap: 0,
margin: {
l: 50,
r: 20,
b: 40,
t: 40
}
}
Plotly.react(divElement, plotData, layout, config)
}
However, the plot looks like this:
Somehow, the first bar was offset so much that it overlaps with the other two, and the other two were not offset enough.
If I remove the offset completely, then the plot looks like this, which is completely wrong.
Question
What did I do wrong? Is there a better approach?
Solution
OK, I accidentally found the solution after trying out randomly.
It seems that the xticks are always in the middle of the bar because offset = -barWidth / 2 is applied by default.
So, simply set the offset to 0 solves the problem.
Answered By - Triet Doan



0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.