我正在使用 Plotly-Dash 并且需要我的文本注释的字体大小与视口宽度一起缩放,就像我的图表一样。对于我的布局中的各种标题,我可以直接设置font-size: '1vw',但vw不是用于设置组件属性的font-size可接受style单位dcc.Graph。这是相关的回溯:
ValueError: Invalid element(s) received for the 'size' property of scatter.textfont 无效元素包括:['1vw', '1vw', '1vw', '1vw', '1vw', '1vw', '1vw' , '1vw', '1vw', '1vw']
The 'size' property is a number and may be specified as: - An int or float in the interval [1, inf] - A tuple, list, or one-dimensional numpy array of the above
我认为如果dcc.Graph组件可以接受视口单位(例如style = {height: 30vw, width: 30vw})并将它们简单地转换为浏览器端的像素,那么我应该能够使用font-size.
Python 端是否有一种方法可以检索视口宽度(以像素为单位),以便我可以为字体大小执行自己的缩放逻辑?
以下是演示此行为的示例 Dash 应用程序:
import dash
from dash.dependencies import Input, Output
import dash_core_components as dcc
import dash_html_components as html
import plotly.graph_objs as go
labels = {'Point 1': (3.5,5), 'Point 2': (1.5,2), 'Point 3': (3.5,8)}
app = dash.Dash(__name__)
app.layout = html.Div([
html.H1('Test', id='test', style={'margin': 50}),
dcc.Graph(id='my-plot', style={'margin': 10}),
])
@app.callback(
Output('my-plot', 'figure'),
[Input('test', 'children')])
def update_graph(val):
return {
'data': [go.Scatter(
x=[v[0]],
y=[v[1]],
text=k,
mode='text'
) for k, v in labels.items()],
'layout': go.Layout(
margin={'l': 40, 'b': 40, 't': 40, 'r': 40},
shapes=[
{
'type': 'path',
'path': ' M 1 1 L 1 3 L 4 1 Z',
'fillcolor': 'rgba(44, 160, 101, 0.5)',
'line': {
'color': 'rgb(44, 160, 101)',
}
},
{
'type': 'path',
'path': ' M 3,7 L2,8 L2,9 L3,10, L4,10 L5,9 L5,8 L4,7 Z',
'fillcolor': 'rgba(255, 140, 184, 0.5)',
'line': {
'color': 'rgb(255, 140, 184)',
}
},
]
)
}
if __name__ == '__main__':
app.run_server()