R语言Plotly绘制环形图时调整图例、扩大绘图区的实现方法
R语言Plotly环形图长文本图例挤占绘图区修复方案
问题场景
使用Plotly绘制环形图时,若分类标签包含百字级长文本,默认图例配置会占用大量画布空间,挤压环形图本身的显示区域。要求在保留原有标题及对应字体设置不变的前提下,缩小图例占用空间、扩大环形图显示尺寸。
原实现代码如下:
library(plotly) library(reshape2) library(dplyr) df<-data.frame(city=c("NYC-The written history of New York City began with the first European explorer, the Italian Giovanni da Verrazzano in 1524. European settlement began with the Dutch in 1608.", "Seattle-Seattle is a seaport city on the West Coast of the United States. It is the seat of King County, Washington. ", "Boston", "LA", "Miami", "Washington"), value=c(100,200,300,400,500,600)) df <-melt(df) fig<-df %>% plot_ly(labels = ~city, values = ~value) fig <- fig %>% add_pie(hole = 0.6) fig <- fig%>% layout(title = "Comparison between of the cities ") fig
修复代码
核心调整分为三块:手动指定环形图绘制域、压缩图例占用空间、削减画布无效边距,全程不改动原有标题配置:
library(plotly) library(reshape2) library(dplyr) df<-data.frame(city=c("NYC-The written history of New York City began with the first European explorer, the Italian Giovanni da Verrazzano in 1524. European settlement began with the Dutch in 1608.", "Seattle-Seattle is a seaport city on the West Coast of the United States. It is the seat of King County, Washington. ", "Boston", "LA", "Miami", "Washington"), value=c(100,200,300,400,500,600)) df <-melt(df) fig<-df %>% plot_ly(labels = ~city, values = ~value) fig <- fig %>% add_pie( hole = 0.6, # 手动指定环形图绘制范围,仅给左侧图例预留窄幅空间 domain = list(x = c(0.18, 0.98), y = c(0.02, 0.95)) ) fig <- fig%>% layout( title = "Comparison between of the cities ", # 图例布局优化 legend = list( x = 0.01, y = 0.5, font = list(size = 9), itemwidth = 25 ), # 压缩画布四周无效边距 margin = list(l = 0, r = 0, t = 40, b = 0) ) fig
关键调整说明
- 在
add_pie中增加domain参数:手动定义环形图在画布上的坐标范围,打破默认自动排布给图例预留过宽空间的问题,直接扩大环形图的可显示尺寸 - 新增
legend配置:将图例固定在画布最左侧垂直居中位置,缩小图例字号、限制图例条目宽度,超长文本自动换行,避免单条长文本撑满整列图例 - 配置
margin参数:削减画布左右、底部的空白边距,仅保留顶部标题所需空间,进一步释放绘图区域 - 全程未修改原有标题的文本、字体相关配置,满足需求约束
内容的提问来源于stack exchange,提问作者silent_hunter
相关产品推荐
相关产品推荐

