我想做什么: 在 Python 中使用 Plotly 绘制折线图,简单的 X 轴和 Y 轴,其中 X 轴包含时间戳。
问题: 折线图转得很奇怪,我怀疑我的顺序不正确。
图表图片:https://imgur.com/tQg6vdl
来自 gross_list 的示例数据(Y 轴):
[146.09, 145.0, 146.09, 152.05, 151.21, 148.26, 150.15, 151.21, 151.21, 151.35]
来自 timestamp_list(X 轴)的样本数据:
'2022-12-06T13:42:09.932+0100', '2022-12-06T13:37:58.288+0100', '2022-12-06T13:40:31.206+0100', '2022-12-06T13:42:47.082+0100', '2022-12-06T13:42:47.082+0100', '2022-12-06T13:41:34.000+0100', '2022-12-06T13:43:55.753+0100', '2022-12-06T13:39:37.648+0100', '2022-12-06T13:42:09.932+0100', '2022-12-06T13:40:00.195+0100', '2022-12-06T13:42:43.677+0100', '2022-12-06T13:42:09.932+0100', '2022-12-06T13:39:37.648+0100', '2022-12-06T13:39:37.648+0100', '2022-12-06T13:41:15.039+0100', '2022-12-06T13:41:15.039+0100', '2022-12-06T13:37:58.288+0100', '2022-12-06T13:40:36.080+0100', '2022-12-06T13:39:05.007+0100', '2022-12-06T13:40:25.363+0100',
import os
import json
from datetime import datetime
import plotly.express as px
import plotly.graph_objects as go
import pandas as pd
# Directory path
dir_path = '/data'
for folder_name in os.listdir(dir_path):
gross_list = []
timestamp_list = []
folder_path = os.path.join(dir_path, folder_name)
if os.path.isdir(folder_path):
json_files = []
for file_name in os.listdir(folder_path):
file_path = os.path.join(folder_path, file_name)
if file_name.endswith('.json'):
with open(file_path, 'r') as json_file:
try:
json_data = json.load(json_file)
json_files.append({
'json': json_data,
'time': datetime.fromtimestamp(os.path.getmtime(file_path))
})
except:
pass
# Sort the JSON files by date and time
json_files.sort(key=lambda x: x['time'])
for json_file in json_files:
data = json_file['json']
gross = data["gross"]
timestamp = data["updated"]
gross_list.append(gross)
timestamp_list.append(timestamp)
x_data = timestamp_list
y_data = gross_list
marker_value = 145
# Create dataframe
df = pd.DataFrame({'x': x_data, 'y': y_data})
# Create line chart
fig = go.Figure()
fig.add_trace(
go.Scatter(
x=df['x'],
y=df['y'],
mode='lines',
line=dict(width=2, shape='linear'),
name='Line Chart'
)
)
# Check if marker value is present in input data
if marker_value not in y_data:
print(f"Marker value {marker_value} is not present in the input data.")
else:
# Add custom marker to the chart
fig.add_trace(
go.Scatter(
x=[df.loc[df['y'] == marker_value, 'x'].values[0]],
y=[marker_value], # Set y value to marker_value to place marker at specified value
mode='markers',
marker=dict(size=6, color='blue', symbol='circle', line=dict(width=2, color='black')),
name=f'Marker at {marker_value}'
)
)
# Add chart title
fig.update_layout(title='Line Chart with Custom Marker')
fig.show()
高度赞赏为什么没有正确订购的任何建议!