Grafana中Plotly图表图例布局适配问题求助
问题
搭建了一个Grafana仪表盘展示家庭电网用电及太阳能板发电情况,其中包含一张日累计发电量图。最初使用Grafana Time Series图表,但无法固定X轴时间区间,改用Plotly实现后图表运行正常,但将面板调整为与Time Series面板尺寸一致时,图例布局出现混乱。想知道能否缩短图例中的线条以适配垂直尺寸,或者让图表区域自动缩容为图例预留空间?
相关实现信息
SQL查询语句(PostgreSQL)
select to_char(time::date,'YYYY-mm-dd') as parameter, now()::date+time::time as time, sum(ppv_total/12) over (partition by time::date order by time) as " " from pv where pv.time > now()::date - interval '7 days' order by time;
查询结果在Grafana中以时间序列处理,生成以parameter值为列名的透视表。
数据处理JS脚本
let dataset = [] for (set =1; set<9; set++){ let x = []; let y = []; data.series[0].fields[set].values.forEach(function (item, index) { if (item > ''){ // 过滤空值 y.push(item/1000); // 转换为kWh(原始数据为Watt) x.push(data.series[0].fields[0].values[index]); } }); if (set == 8){ // 突出显示今日数据 line={width:4, color: "yellow"}; }else{ line={width:1}; } let serie = { x : x, y : y, name : data.series[0].fields[set].labels.parameter, line: line }; dataset.push(serie) } return { data : dataset, config : { displayModeBar: false } }
Grafana Layout配置
{ "yaxis": { "gridcolor": "#344", "autorange": true, "color": "#444", "type": "linear", "range": [ -0.3900152777777779, 7.49179027777778 ] }, "xaxis": { "type": "date", "gridwidth": 1, "gridcolor": "#344", "autorange": true, "color": "#444", "range": [ "2024-03-26 07:49:19", "2024-03-26 19:40:08" ] }, "annotations": [ { "showarrow": false, "text": "kWh", "textangle": -90, "x": -0.03, "xanchor": "right", "xref": "paper", "y": 0.5, "yanchor": "right", "yref": "paper" } ], "font": { "color": "darkgrey" }, "hovermode": "closest", "margin": { "b": 10, "t": 15, "r": 10, "l": 40 }, "paper_bgcolor": "rgba(0,0,0,0)", "plot_bgcolor": "rgba(0,0,0,0)", "legend": { "orientation": "h", "yanchor": "bottom", "y": -0.5, "xanchor": "mid", "x": 0, "entrywidth": 20 } }
解决方案
1. 缩短图例中的线条长度
你已经在Layout的legend配置中设置了entrywidth:20,这个参数直接控制图例条目(含线条+文字)的总宽度。如果线条仍显过长,可进一步减小该值,同时显式指定单位为像素(默认已是像素,显式设置更稳妥):
"legend": { "orientation": "h", "yanchor": "bottom", "y": -0.5, "xanchor": "mid", "x": 0, "entrywidth": 15, "entrywidthmode": "pixels" }
另外,可通过tracegroupgap调整图例组间距,避免条目拥挤:
"legend": { // 保留原有配置 "tracegroupgap": 2 }
2. 让图表区域自动缩容为图例预留空间
当前margin.b(底部边距)设为10,不足以容纳底部水平布局的图例。增大底部边距,图表区域会自动向上收缩,为图例留出空间:
"margin": { "b": 40, "t": 15, "r": 10, "l": 40 }
同时调整图例的y值,让它更靠近图表底部,减少空间浪费:
"legend": { "orientation": "h", "yanchor": "bottom", "y": -0.3, "xanchor": "mid", "x": 0, "entrywidth": 20 }
3. 额外优化建议
如果图例条目过多导致水平布局仍拥挤,可改为垂直布局,同时调整侧边距容纳图例:
"legend": { "orientation": "v", "yanchor": "top", "y": 1, "xanchor": "right", "x": 1.05, "entrywidth": 20 }, "margin": { "b": 10, "t": 15, "r": 60, // 增大右侧边距 "l": 40 }
内容的提问来源于stack exchange,提问作者MortenSickel
相关产品推荐
相关产品推荐

