Plotly可视化图表优化求助:消除首尾间隙与解决坐标轴刻度标签重叠问题
Hey Leonardo, I’ve looked at your code and those two issues are totally fixable with a few simple adjustments to your Plotly layout settings. Let’s break them down one by one:
1. Removing Empty Gaps at the Start/End of the Chart
The gaps happen because Plotly automatically adds padding to the x-axis range by default. To fix this, we’ll manually lock the x-axis range to exactly match the minimum and maximum datetime values in your data.
First, calculate the min and max times from your time_seconds column (converted to datetime):
min_time = pd.to_datetime(table['time_seconds'].min(), unit='s') max_time = pd.to_datetime(table['time_seconds'].max(), unit='s')
Then, add this range constraint to your update_layout call—this eliminates the unwanted padding:
xaxis={ "range": [min_time, max_time], "tickformat": "%H:%M:%S", # Optional: Rotate x-ticks if they still overlap "tickangle": -45 }
2. Fixing Overlapping Axis Tick Labels
Looking at your code, the right y-axis (yaxis2) has dtick=1, which is way too small for your opt1 values (range ~0.9 to 1.25). This causes the tick labels to stack on top of each other. We’ll adjust the dtick value to something more appropriate for your data range.
For yaxis2, change dtick=1 to dtick=0.1—this creates clean, spaced-out ticks for your opt1 values. If you prefer Plotly to handle tick spacing automatically, you can even remove the dtick parameter entirely, but setting a manual value gives you more control.
For the left y-axis (used by opt2 and opt3), if ticks ever overlap, you can use the same approach: adjust dtick or add tickangle to rotate labels.
Full Fixed Code
Here’s your updated code with both fixes applied:
import pandas as pd import plotly.express as px data_dict = [{'variable': 'opt1', 'time_seconds': 62.42, 'values': 1.2506616294386024}, {'variable': 'opt1', 'time_seconds': 368.64, 'values': 1.026396270065788}, {'variable': 'opt1', 'time_seconds': 672.04, 'values': 0.9193268790432114}, {'variable': 'opt1', 'time_seconds': 967.76, 'values': 1.0040146519632747}, {'variable': 'opt1', 'time_seconds': 1319.24, 'values': 0.9758039569410012}, {'variable': 'opt1', 'time_seconds': 1621.84, 'values': 0.9608018775714326}, {'variable': 'opt2', 'time_seconds': 62.42, 'values': 53.669690262026634}, {'variable': 'opt2', 'time_seconds': 368.64, 'values': 67.29353920559024}, {'variable': 'opt2', 'time_seconds': 672.04, 'values': 82.30782533848364}, {'variable': 'opt2', 'time_seconds': 1017.26, 'values': 64.92250125677477}, {'variable': 'opt2', 'time_seconds': 1319.24, 'values': 61.70492445574225}, {'variable': 'opt2', 'time_seconds': 1621.84, 'values': 66.73124984237081}, {'variable': 'opt3', 'time_seconds': 62.34, 'values': 67.07091129789107}, {'variable': 'opt3', 'time_seconds': 364.74, 'values': 60.39192699523444}, {'variable': 'opt3', 'time_seconds': 666.68, 'values': 57.13104540996532}, {'variable': 'opt3', 'time_seconds': 967.76, 'values': 50.293945860615096}, {'variable': 'opt3', 'time_seconds': 1317.33, 'values': 73.49109300734065}, {'variable': 'opt3', 'time_seconds': 1619.03, 'values': 80.53859104682748}] table = pd.DataFrame.from_dict(data_dict) # Calculate min/max time to lock x-axis range min_time = pd.to_datetime(table['time_seconds'].min(), unit='s') max_time = pd.to_datetime(table['time_seconds'].max(), unit='s') px.scatter( table, x=pd.to_datetime(table['time_seconds'],unit='s'), y="values", color="variable", hover_data=["time_seconds"], color_discrete_map={ "opt1": "#008aff", "opt2": "#8c2eff", "opt3": "#56cb32", }, ).update_traces(mode="lines+markers").for_each_trace( lambda t: t.update(yaxis="y2") if t.name == "opt1" else t ).update_layout( yaxis2={"overlaying": "y", "side": "right", "dtick": 0.1}, # Adjusted dtick for non-overlapping ticks xaxis={ "range": [min_time, max_time], # Remove x-axis padding gaps "tickformat": "%H:%M:%S", "tickangle": -45 # Optional: Rotate x-ticks to prevent overlap }, showlegend=False, title_text=None, )
Extra Tips
- If you want a tiny bit of padding on the x-axis (instead of zero), adjust the min/max times slightly (e.g., subtract 60 seconds from
min_timeand add 60 tomax_time). - For stubborn overlapping ticks, try
tickmode="array"to manually specify which tick values to display, or reduce the font size withtickfont={"size": 10}.
内容的提问来源于stack exchange,提问作者Leonardo Ferreira

