Plotly环形图分面图创建遇重叠问题求助
解决Plotly环形图分面重叠问题
你的代码出现重叠是因为每个环形图默认占据整个绘图区域,subplot无法自动调整它们的位置。下面是两种可行的修复方案:
方案一:为每个环形图指定Domain范围
在add_pie中通过domain参数明确每个图的位置,让它们在分面中各自占据一半空间:
library(plotly) library(dplyr) # 预处理数据 mtcars$manuf <- sapply(strsplit(rownames(mtcars), " "), "[[", 1) df <- mtcars %>% group_by(manuf) %>% summarize(count = n()) # 环形图1:占据左侧50%区域 fig <- df %>% plot_ly(labels = ~manuf, values = ~count) %>% add_pie(hole = 0.6, domain = list(x = c(0, 0.45), y = c(0, 1))) %>% # 设置左侧范围 layout( title = "Donut charts using Plotly 1", showlegend = FALSE, # 关闭单个图的图例,避免重复 xaxis = list(showgrid = FALSE, zeroline = FALSE, showticklabels = FALSE), yaxis = list(showgrid = FALSE, zeroline = FALSE, showticklabels = FALSE) ) # 环形图2:占据右侧50%区域 fig1 <- df %>% plot_ly(labels = ~manuf, values = ~count) %>% add_pie(hole = 0.6, domain = list(x = c(0.55, 1), y = c(0, 1))) %>% # 设置右侧范围 layout( title = "Donut charts using Plotly 2", showlegend = TRUE, # 只保留一个图例 xaxis = list(showgrid = FALSE, zeroline = FALSE, showticklabels = FALSE), yaxis = list(showgrid = FALSE, zeroline = FALSE, showticklabels = FALSE) ) # 合并分面 facet_fig <- subplot(fig, fig1, nrows = 1, margin = 0.05) facet_fig
方案二:使用统一布局简化代码
不用单独创建两个图,直接在同一个plotly对象中添加两个pie层,通过domain分配位置,再调整整体布局:
library(plotly) library(dplyr) mtcars$manuf <- sapply(strsplit(rownames(mtcars), " "), "[[", 1) df <- mtcars %>% group_by(manuf) %>% summarize(count = n()) facet_fig <- plot_ly() %>% # 添加第一个环形图 add_pie(data = df, labels = ~manuf, values = ~count, hole = 0.6, domain = list(x = c(0, 0.45), y = c(0, 1)), name = "Donut 1") %>% # 添加第二个环形图 add_pie(data = df, labels = ~manuf, values = ~count, hole = 0.6, domain = list(x = c(0.55, 1), y = c(0, 1)), name = "Donut 2") %>% # 整体布局设置 layout( title = "Faceted Donut Charts", showlegend = TRUE, annotations = list( list(x = 0.225, y = 1.05, text = "Donut charts using Plotly 1", showarrow = FALSE), list(x = 0.775, y = 1.05, text = "Donut charts using Plotly 2", showarrow = FALSE) ), xaxis = list(showgrid = FALSE, zeroline = FALSE, showticklabels = FALSE), yaxis = list(showgrid = FALSE, zeroline = FALSE, showticklabels = FALSE) ) facet_fig
关键说明
domain参数用于控制每个pie图在绘图区域的位置范围,x和y分别对应水平和垂直方向的比例(0到1之间)。- 关闭其中一个图的图例,避免分面后出现重复图例,提升视觉整洁度。
- 第二种方案更简洁,通过在同一个plot对象中添加多个层来实现分面,减少冗余代码。
内容的提问来源于stack exchange,提问作者silent_hunter
相关产品推荐
相关产品推荐

