如何在图中更改注释方向?

时间:2019-03-27 07:56:55

标签: python plotly data-visualization plotly.js

说我有下图:

import numpy as np
import plotly.graph_objs as go

z=np.random.randint(1000, 11000, size=20)
trace=dict(type='scatter',
          x=3+np.random.rand(20),
          y=-2+3*np.random.rand(20),
          mode='markers',
          marker=dict(color= z, 
                      colorscale='RdBu', size=14, colorbar=dict(thickness=20)))

axis_style=dict(zeroline=False, showline=True, mirror=True)
layout=dict(width=550, height=500,
            xaxis=axis_style,
            yaxis=axis_style,
            hovermode='closest',

           )
fig=go.FigureWidget(data=[trace], layout=layout)
fig

enter image description here

现在说我希望颜色条具有标题。由于plotly目前尚无直接方法来执行此操作,因此,如果我理解正确,我将通过annotations进行操作,如图here所示:

layout.update(
    annotations=[dict(
          x=1.12,
          y=1.05,
          align="right",
          valign="top",
          text='Colorbar Title',
          showarrow=False,
          xref="paper",
          yref="paper",
          xanchor="center",
          yanchor="top"
        )
    ]
) 

我们可以看到,出现了彩条标题:

fig=go.FigureWidget(data=[trace], layout=layout)
fig

enter image description here

但是,现在说我想沿着颜色条将颜色条标题横向放置,就像这样:

enter image description here

我该怎么做?

1 个答案:

答案 0 :(得分:1)

参数textangle为您完成。 Example来自plotly文档。根据需要设置textangle=-90旋转注释。

代码:

# import necessaries libraries
import numpy as np
import plotly.offline as py
import plotly.graph_objs as go

z = np.random.randint(1000, 11000, size=20)
# Create a trace
trace = dict(type='scatter',
             x=3+np.random.rand(20),
             y=-2+3*np.random.rand(20),
             mode='markers',
             marker=dict(color=z, colorscale='RdBu',
                         size=14, colorbar=dict(thickness=20)))
# Define axis_style
axis_style = dict(zeroline=False, showline=True, mirror=True)
# Specify layout style
layout = dict(width=550, height=500,
              xaxis=axis_style,
              yaxis=axis_style,
              hovermode='closest',
              )
# Update layout with annotation
layout.update(
    annotations=[dict(
          # Don't specify y position,because yanchor="middle" do it for you
          x=1.22,
          align="right",
          valign="top",
          text='Colorbar Title',
          showarrow=False,
          xref="paper",
          yref="paper",
          xanchor="right",
          yanchor="middle",
          # Parameter textangle allow you to rotate annotation how you want
          textangle=-90
        )
    ]
)
# Create FigureWidget
fig = go.FigureWidget(data=[trace], layout=layout)
# Plot fig
py.plot(fig)

输出:

Plot