我正在尝试创建多个折线图,其中包含 Chart JS 和 Flask 中的每日、每月和活跃用户。例如,我希望第一个图表显示前 30 天每天的用户数。这是下面的代码:
路线
# set default time period
time_period = 'daily'
# calculate start and end time based on time period
end_time = datetime.now()
if time_period == 'daily':
start_time = end_time - timedelta(days=29)
print(start_time)
step = timedelta(days=1)
date_format = '%d %b %Y'
label_format = '%d %b %Y'
elif time_period == 'weekly':
start_time = end_time - timedelta(weeks=51)
print(start_time)
step = timedelta(weeks=1)
date_format = '%d %b %Y'
label_format = '%d %b %Y'
elif time_period == 'monthly':
start_time = end_time - timedelta(days=364)
print(start_time)
step = timedelta(days=30)
date_format = '%b %Y'
label_format = '%b %Y'
# query user sessions
sessions = UserSession.query.filter(
UserSession.start_time >= start_time,
UserSession.end_time <= end_time
).all()
# calculate number of users
user_counts = {}
for session in sessions:
session_date = session.start_time.date()
if session_date not in user_counts:
user_counts[session_date] = set()
user_counts[session_date].add(session.user_id)
# create a list of dates and user counts
date_list = []
user_count_list = []
for date in user_counts.keys():
date_list.append(date)
user_count_list.append(len(user_counts[date]))
# create a list of labels
label_list = []
current_date = start_time
while current_date <= end_time:
if time_period == 'monthly':
label_list.append(current_date.strftime(label_format))
else:
label_list.append(current_date.strftime(date_format))
current_date += step
data_dict = {
'daily': {'label': 'Daily Users', 'data': user_count_list[-30:], 'labels': label_list[-29:], 'date_format': date_format},
'weekly': {'label': 'Weekly Users', 'data': [sum(user_count_list[i:i+7])/7 for i in range(len(user_count_list)-52, len(user_count_list), 7)], 'labels': label_list[-52:], 'date_format': date_format},
'monthly': {'label': 'Monthly Users', 'data': [sum(user_count_list[i:i+30])/30 for i in range(len(user_count_list)-365, len(user_count_list), 30)], 'labels': label_list[-12:], 'date_format': date_format}
}
金贾
<div class="chart-container">
<canvas id="myChart"style="height: 300px;"></canvas>
</div>
<script>
// Get data from Flask
var data = {{ data_dict['daily']|tojson }};
// Create new Chart instance
var ctx = document.getElementById('myChart').getContext('2d');
var myChart = new Chart(ctx, {
type: 'line',
data: {
labels: data['labels'],
datasets: [{
label: data['label'],
data: data['data'],
backgroundColor: 'rgba(0, 119, 204, 0.3)',
borderColor: 'rgba(0, 119, 204, 1)',
borderWidth: 1
}]
},
options: {
responsive: true,
maintainAspectRatio: false,
scales: {
x: {
ticks: {
callback: function(value, index, values) {
return moment(value, data['date_format']).format('DD MMM YYYY');
}
}
},
y: {
ticks: {
beginAtZero: true,
precision: 0,
}
}
},
legend: {
display: false
},
title: {
display: true,
text: 'Daily User Sessions'
}
}
});
</script>
我面临的问题是它显示前 4 天(带有错误的刻度),然后显示未来的无效日期。我将在下面发布屏幕截图进行演示。