如何用R语言plotly绘制足球赛事统计双向条形图
解决方案
可以通过R的plotly实现目标效果,两个问题的解决方法如下:
核心解决思路
- 子图中间空白:手动配置两个x轴的
domain参数,分别限定左右子图的水平显示范围,压缩中间空白区域,不需要完全依赖subplot的margin参数。 - 文本定位:
- 统计项名称用画布全局(paper)坐标系定位,固定放在两个子图的中间位置
- 两队对应数值直接绑定到条形图层,通过
textposition参数调整显示在条形靠近中间的一侧
完整可运行代码
# 加载依赖包 library(plotly) library(dplyr) # 模拟数据集 team_1 <- c(rep("team_1", 4)) team_2 <- c(rep("team_2",4)) statistics <- c("shots", "passes", "offsides", "corners") values_team_1 <- c(5, 120, 5, 2) values_team_2 <- c(10, 400, 0, 7) dummy_frame <- data.frame( team_1, statistics, values_team_1, values_team_2, team_2 ) dummy_frame <- dummy_frame %>% mutate(values_team_1_rel = values_team_1 / (values_team_1 + values_team_2), values_team_2_rel = values_team_2 / (values_team_1 + values_team_2)) # 左侧team1条形图,直接绑定数值文本 barplot_team_1 <- plot_ly(dummy_frame, x = ~ values_team_1_rel * (-1), y = ~ statistics, type = "bar", orientation = "h", name = "team_1", text = ~values_team_1, # 显示实际数值 textposition = "outside", # 显示在条形靠近中间的一侧 insidetextanchor = "end", marker = list(color = "#1f77b4")) # 右侧team2条形图,绑定数值文本 barplot_team_2 <- plot_ly(dummy_frame, x = ~ values_team_2_rel, y = ~ statistics, type = "bar", orientation = "h", name = "team_2", text = ~values_team_2, textposition = "outside", insidetextanchor = "start", marker = list(color = "#ff7f0e")) subplot(barplot_team_1, barplot_team_2, shareY = TRUE, margin = 0) %>% layout( barmode = 'grouped', # 限定左侧x轴显示范围为画布的0到48%位置 xaxis = list(title = "", showticklabels = FALSE, domain = c(0, 0.48), zeroline = FALSE), # 限定右侧x轴显示范围为画布的52%到100%位置,中间仅留4%的间隙放统计项 xaxis2 = list(title = "", showticklabels = FALSE, domain = c(0.52, 1), zeroline = FALSE), yaxis = list(title ="", showticklabels = FALSE) ) %>% # 添加统计项文本,用paper坐标系,x=0.5就是画布正中间 add_annotations(x = 0.5, y = dummy_frame$statistics, text = dummy_frame$statistics, xref = "paper", yref = "y", showarrow = FALSE, font = list(size = 12))
内容的提问来源于stack exchange,提问作者sy_MRZ
相关产品推荐
相关产品推荐

