OiO.lk Blog python Does Plotly has troubles plotting images when the x-axis is in date format?
python

Does Plotly has troubles plotting images when the x-axis is in date format?


I have been trying to plot an image as a marker in a plotly graph and haven’t been able to achieve this successfully.

If I plot the image using integers for x axis everything seems to work fine:

fig = go.Figure()

pyLogo = Image.open(sell_icon_path)

# Add trace
fig.add_trace(
    go.Scatter(x=[0, 0.5, 1, 2, 2.2], y=[1.23, 2.5, 0.42, 3, 1])
)

fig.add_layout_image(
        dict(
            source=pyLogo,
            xref="x",
            yref="y",
            x=1,
            y=0.5,
            sizex=2,
            sizey=2,
            sizing="contain",
            opacity=1,
            layer="above",
            xanchor="center",
            yanchor="middle")
)

fig.show()

Resulting in this:

code working

But when I try to plot the same image, using the same path having datetimes in the x-axis this is not working.

sal = prop_info['sal']

# Series
months = mp.dat
us_data = mp.value

# Prepare DataFrame for line plot
df = pd.DataFrame({
    'month': months,
    f'{sal}': us_data,
})

# Keep 'month' as timestamp, but use only the year and month
df['month'] = pd.to_datetime(df['month']).dt.to_period('M').dt.to_timestamp()

# Extract median date and price for positioning the image
med_date = df['month'].iloc[10]
med_price = df[sal].iloc[10]

# Plot Series
fig = go.Figure()

# Add trace using 'month' as x-axis
fig.add_trace(
    go.Scatter(x=df['month'], y=df[sal].to_list())
)

pyLogo = Image.open(sell_icon_path)

# Use datetime for xref="x" and yref="y"
fig.add_layout_image(dict(
    source=pyLogo,
    xref="x",  # Use 'x' axis referencing dates
    yref="y",  # Use 'y' axis referencing prices
    x=med_date,  # Still using datetime for x
    y=med_price,  # Price value for y
    sizex=0.1,  # Adjust size to fit the plot
    sizey=0.1,
    sizing="contain",
    opacity=1,
    layer="above",
    xanchor="center",
    yanchor="middle"))

fig.show()

code not working

I don’t know if there is another way to handle this, I’ve already tried using timestamps for the x-axis.

I have already tried with timestamps, datetime, etc.



You need to sign in to view this answers

Exit mobile version