首页 > 解决方案 > Plotly control relative lengths of each axis

问题描述

maybe there is something in the documentation that I missed, but how do I control the relative length of each axis, so that the plot is a square? I am basically looking for the equivalent of matlabs

pbaspect([1 1 1])

This is the current image enter image description here

which I want to turn into this (ignore the additional axis labels): enter image description here

I made the change by manually setting the image size, but there has to be an easier way to do it.

fig.update_yaxes(scaleanchor = "x",scaleratio = 1,)

Does not work since the axes are using different numbers. I am happy about any suggestions.

标签: pythonplotlyplotly-python

解决方案


it's as simple as setting the height and width as the same

import plotly.graph_objects as go
import numpy as np

go.Figure(go.Scatter(x=np.linspace(0,100,1000), y=np.random.uniform(0,5,1000), mode="markers"), layout={"height":400, "width":400})

approach 2 - use HTML view port heigh / width

  • css width same as height technique can be used
  • create a <div> that is sized in same view port units. embed plotly html within this sized <div>
import plotly.express as px
import io

buffer = io.StringIO()

go.Figure(
    go.Scatter(
        x=np.linspace(0, 100, 1000),
        y=np.random.uniform(0, 5, 1000) * np.random.uniform(0, 1, 1000),
        mode="markers",
    )
).update_layout(margin={"t":0,"b":30,"l":0,"r":0}).write_html(buffer, full_html=False)


# use HTML techniques create a "square", NB height and width defined in same view port units
html = '<div style="width: 70vh; height: 70vh;">' + buffer.getvalue().encode().decode() + "</div>"
with open("example.html", "w") as f: f.write(html)

# not required if not running in jupyter
from IPython.core.display import display, HTML
HTML(html)


推荐阅读