如何增大ggplotly图例中颜色图标的尺寸?
调整ggplotly图例颜色图标的尺寸,使其接近静态ggplot样式
我用ggplotly绘制了热力图,发现图例中的颜色图标相比静态ggplot图表显得非常纤细,如何调整以增大这些图标尺寸,让呈现效果接近静态ggplot中的样式?
示例代码
dat <- structure(list(Date = structure(c(1640995200, 1643673600, 1646092800, 1648771200, 1651363200, 1654041600, 1656633600, 1659312000, 1661990400 ), tzone = "UTC", class = c("POSIXct", "POSIXt")), Variable = c("Zinc concentrate production volume (tons)", "Zinc concentrate production volume (tons)", "Zinc concentrate production volume (tons)", "Zinc concentrate production volume (tons)", "Zinc concentrate production volume (tons)", "Zinc concentrate production volume (tons)", "Zinc concentrate production volume (tons)", "Zinc concentrate production volume (tons)", "Zinc concentrate production volume (tons)" ), Value = c(0.176935645322967, 1.09984311986, 0.696173307906093, -0.757110090664708, -2.39009319660863, -0.924763914389984, -0.962968019123352, -1.79683715589855, 0.0254350069494616), Color = structure(c(3L, 2L, 3L, 4L, 6L, 4L, 4L, 5L, 3L), levels = c("#0a5d00", "#0eff00", "#ece75f", "#FFBF00", "#ff0000", "#7b0000"), class = c("ordered", "factor")), Label = structure(c(3L, 2L, 3L, 4L, 6L, 4L, 4L, 5L, 3L), levels = c("> 2 Standard Deviations from mean", "1 to 2 Standard Deviations from mean", "0 to 1 Standard Deviations from mean", "0 to -1 Standard Deviations from mean", "-1 to -2 Standard Deviations from mean", "> -2 Standard Deviations from mean" ), class = c("ordered", "factor"))), row.names = c(NA, -9L), class = c("tbl_df", "tbl", "data.frame")) dat %>% { ggplot(.,aes(Date, Variable, fill = Label)) + geom_tile(col = 'white') + theme_light() + scale_fill_manual(values = levels(as.factor(.$Color)), breaks = levels(as.factor(.$Label))) + theme(axis.text = element_text(face="bold")) } %>% ggplotly(tooltip = c('Date','Label')) %>% layout(legend = list(xanchor = "left", y = -.2, x = -.2, orientation = "h", title = list(text = "")))
当前与期望效果
- 当前ggplotly图例效果:

- 期望的静态ggplot图例效果:

解决方案
通过在layout的legend参数中添加itemwidth和itemheight,可以直接调整图例图标的宽高,让其更接近静态ggplot的方形样式。同时可配合tracegroupgap优化图例项的间距:
dat %>% { ggplot(.,aes(Date, Variable, fill = Label)) + geom_tile(col = 'white') + theme_light() + scale_fill_manual(values = levels(as.factor(.$Color)), breaks = levels(as.factor(.$Label))) + theme(axis.text = element_text(face="bold")) } %>% ggplotly(tooltip = c('Date','Label')) %>% layout(legend = list(xanchor = "left", y = -.2, x = -.2, orientation = "h", title = list(text = ""), itemwidth = 30, # 增大图标宽度 itemheight = 15, # 增大图标高度 tracegroupgap = 10)) # 调整图例项间距
参数说明:
itemwidth:控制图例图标的宽度,数值越大图标越宽itemheight:控制图例图标的高度,数值越大图标越高tracegroupgap:水平图例下,控制不同图例项之间的垂直间距,让布局更宽松
可以根据实际需求调整这几个参数的数值,直到达到接近静态ggplot的视觉效果。
内容的提问来源于stack exchange,提问作者Tanga94
相关产品推荐
相关产品推荐

