[英]How do I use dates from a LinkedHashMap for the x-axis on a Highcharts line graph (using Thymeleaf)?
我是使用 Highcharts 的新手,所以這可能是一個微不足道的問題。 但是,通過我自己的谷歌搜索,我並沒有取得太大的成功。
我試圖獲得一個折線圖來顯示強度隨時間的進展,但每次我插入 keySet()(類型為 java.util.Date)作為 X 軸上的內容時,圖表從 web 中消失頁。
我希望正在完成的事件的記錄和它完成的日期成為圖表上的一個點(即(x,y)將是(動作,日期))。
Java 東西:
List<StrengthProgressPoint> records = getAllStrengthLogsForExercise(session, exerciseName);
Map<Date, Double> strengthGraph = new LinkedHashMap<>();
for(StrengthProgressPoint p : records) {
strengthGraph.put(p.getDate(), p.getWeight());
}
Highcharts 東西:
<script>
$(function () {
$('#progressGraphContainer').highcharts({
title: {
text: ''
},
subtitle: {
text: ''
},
yAxis: {
min: 0,
title: {
text: 'Weight Lifted'
}
},
xAxis: {
categories: [[${strengthGraph.keySet()}]],
},
legend: {
enabled: false
},
plotOptions: {
series: {
label: {
connectorAllowed: false,
connectNulls: true
},
}
},
series: [{
name: 'Weight',
data: [[${strengthGraph.values()}]]
}],
responsive: {
rules: [{
condition: {
maxWidth: 500
},
chartOptions: {
legend: {
enabled: false
}
}
}]
}
});
});
</script>
我確實在我的 web 頁面上顯示了幾次圖表,但從來沒有我想要的。 我似乎已將其范圍縮小到“類別:[[${strengthGraph.keySet()}]]”是導致圖表無法顯示在 web 頁面上的罪魁禍首。 我只希望 HashMap 中的日期顯示在 x 軸上(當然對應於適當的值)。
因為您使用 Thymeleaf 和 JavaScript,所以您需要在<script>
標記中指出這一點:
<script th:inline="javascript">
沒有這個,從您的 Java 對象到等效的 JavaScript 對象的渲染將不會發生。
我假設您已經在頁面的<html>
標記中包含了 Thymeleaf 命名空間:
<html xmlns:th="http://www.thymeleaf.org">
日期將顯示在 x 軸上 - 但格式可能有點麻煩 - 例如:
2021-03-15T00:00:00.000-04:00
因此,您可以添加 label 格式化程序。 格式化日期的方法有很多,我希望 HighCharts 有內置的方法來做到這一點,但我對它們並不熟悉 - 所以這是一個簡單的 JavaScript 方式:
xAxis: {
categories: [[${strengthGraph.keySet()}]],
labels: {
formatter: function () {
var d = Date.parse(this.value);
const ye = new Intl.DateTimeFormat('en', {year: 'numeric'}).format(d);
const mo = new Intl.DateTimeFormat('en', {month: 'short'}).format(d);
const da = new Intl.DateTimeFormat('en', {day: '2-digit'}).format(d);
return `${da}-${mo}-${ye}`;
}
}
},
...
現在軸將使用如下標簽:
15-Mar-2021
我從這個問題中獲取了這個格式化程序代碼,還有其他方法。
Worth mentioning: When you place Thymeleaf expressions in JavaScript, you can suppress JavaScript syntax errors by placing the Thymeleaf expression inside comments - and by also providing a default value in its place:
categories: /*[[${strengthGraph.keySet()}]]*/ []
在這種情況下, []
是默認值。 當 Thymeleaf 渲染表達式時,它會刪除/*
和*/
注釋分隔符,同時也會刪除默認表達式。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.