如何在R Markdown的flexdashboard中让Plotly仪表盘数值与刻度盘均居中
在flexdashboard中居中Plotly仪表盘的问题
我在R Markdown的flexdashboard里使用Plotly制作仪表盘,编织生成HTML文件后,仪表盘的数值会出现偏移,但刻度盘始终保持居中。如何让所有元素都保持居中且位置固定?
补充说明:以下是其中一个仪表盘的代码:
plot_ly( type = "indicator", mode = "gauge+number", align = "center", value = round(100*data_open,1), number = list(suffix = "%", valueformat = "center", textAlign= 'center'), gauge = list( font = list(color = "black", family = "Open Sans", size = 16), axis = list( range = list(0,100), tickvals = list(0,20,40,60,80,90,100), tickwidth = 1, tickcolor = "black"), bar = list(color = "lightgrey", thickness = .20, line = list(width = 4)), borderwidth = 2, bordercolor = "lightgrey", steps = list( list(range = c(0,20), color = "#490f52"), list(range = c(20,40), color = "#5d2a65"), list(range = c(40,60), color = "#87618d"), list(range = c(60,80), color = "#b198b4"), list(range = c(80,90), color = "#c6b3c8"), list(range = c(90,100), color = "#d7cad9")), threshold = list( line = list(color = "darkgrey", width = 4), thickness = 0.75, value = round(100*data_open,1))), height = 200) %>% layout(margin = list(autoexpand =FALSE, l = 30, r = 45, t = 20, b = 55), font = list(color = "black", family = "Open Sans", textAlign= 'center', size = 15)) %>% config(displayModeBar = F)
解决方法
数值偏移的核心问题是无效参数配置和不对称边距导致的,调整以下几点即可修复:
- 移除无效参数:根层级的
align = "center"、number里的valueformat = "center"都是Plotly indicator类型不支持的参数,直接删除。 - 统一数值对齐:仅保留
number中的textAlign = 'center',确保数值强制居中。 - 设置对称边距:原布局中左右边距
l=30, r=45不一致,会导致整体偏移,改成l=35, r=35这类对称值,保证仪表盘在容器中居中。
修改后的代码如下:
plot_ly( type = "indicator", mode = "gauge+number", value = round(100*data_open,1), number = list(suffix = "%", textAlign= 'center'), gauge = list( font = list(color = "black", family = "Open Sans", size = 16), axis = list( range = list(0,100), tickvals = list(0,20,40,60,80,90,100), tickwidth = 1, tickcolor = "black"), bar = list(color = "lightgrey", thickness = .20, line = list(width = 4)), borderwidth = 2, bordercolor = "lightgrey", steps = list( list(range = c(0,20), color = "#490f52"), list(range = c(20,40), color = "#5d2a65"), list(range = c(40,60), color = "#87618d"), list(range = c(60,80), color = "#b198b4"), list(range = c(80,90), color = "#c6b3c8"), list(range = c(90,100), color = "#d7cad9")), threshold = list( line = list(color = "darkgrey", width = 4), thickness = 0.75, value = round(100*data_open,1))), height = 200) %>% layout(margin = list(autoexpand = FALSE, l = 35, r = 35, t = 20, b = 55), font = list(color = "black", family = "Open Sans", size = 15)) %>% config(displayModeBar = F)
如果有多个仪表盘,建议统一使用相同的边距配置,保证整体布局一致性。
内容的提问来源于stack exchange,提问作者c_marie
相关产品推荐
相关产品推荐

