Search code examples
pythonpdfplotplotly

How do I prevent Plotly from reducing the number of points in a line when exporting to PDF?


I am using the python plotly package to generate plots for a thesis. I export the figures with the fig.write_image() command. However, the number of points used to describe a line scatter plot reduces when exporting to pdf (or svg or eps). In my jupyter notebook, the curve looks smooth, exported as pdf, I clearly see the "dots".

Picture of the PDF opened in a vector graphics software

Here is a minimal example:

import plotly.graph_objects as go
import numpy as np

xvalues=np.linspace(0,10,10000)

fig=go.Figure()
fig.add_trace(go.Scatter(x=xvalues, y=np.sin(xvalues), name="sin(x) marker", mode='markers', marker=dict(size=1)))
fig.add_trace(go.Scatter(x=xvalues, y=np.cos(xvalues), name="cos(x) line", ))

fig.show()
fig.write_image("cos.pdf")

I have used different formats such as svg or eps with the same result. Also the software to open the file doesn't affect the plot. When exporting as png, the curve looks smooth.

Is this a bug or a feature? I assume this is some sort of compression?

A workaround is to switch from a line type to markers and increase the number of points accordingly. However, I am not sure if this is a good solution in terms of file size. Furthermore, this requires some fiddeling with the legend to get a line instead of a dot.

I want to include the plots in a Latex document. I would be fine changing the file format as necessary as long as it remains a vector graphic.


Solution

  • You need to set the line shape to "spline". Default is "linear" (points are linked by straight lines).

    shape - Determines the line shape. With "spline" the lines are drawn using spline interpolation. The other available values correspond to step-wise line shapes.

    fig.add_trace(go.Scatter(
       x=xvalues, y=np.cos(xvalues), name="cos(x) line", line=dict(shape='spline')
    ))
    

    Note that by using spline interpolation, you can reduce the number of points without impacting the smoothness of the curve.