You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Plotly-R修改图例显示内容及调整子图间距技术求助

Solution to Your Plotly-R Questions

Hey Anna, great job diving into Plotly-R for your inequality metric visualizations! Let’s work through those two issues you’re facing step by step:

1. Update Legend to Show Years (Instead of Metric Names)

The core problem here is that your original code tied symbols to metric values instead of a dedicated year variable, and grouped traces by metric names. To fix this, we’ll restructure your data to include explicit year labels, then map symbols and legend names directly to those years.

Key Fixes:

  • Add a year column to each metric’s data frame (so we have a clear variable to link symbols to)
  • Set symbol = ~year and name = ~year in each trace, so the legend displays the year corresponding to each symbol
  • Keep your desired symbol mapping: circle=2018, x=2019, o=2020

2. Add Spacing Between Subplots

Plotly’s subplot() function has a spacing parameter that controls gaps between plots (values range from 0 to 1, where higher values mean larger gaps). For 1-2 cm of spacing, start with spacing = 0.1 (you can tweak this based on your output size—adjust up to 0.15 for wider gaps if needed).

Full Modified Code

library(plotly)

# Restructure data to include explicit year labels
gini <- data.frame(year = c(2018, 2019, 2020), value = c(0.4, 0.3, 0.2))
palma <- data.frame(year = c(2018, 2019, 2020), value = c(1.2, 1.1, 1.0))
S <- data.frame(year = c(2018, 2019, 2020), value = c(5.2, 5.1, 5.0))

# Build each subplot with correct symbol/legend mapping
p <- plot_ly(gini, x = "Coeff. di Gini", y = ~value, alpha = 0.7) %>%
  add_trace(
    symbol = ~year,
    symbols = c('circle','x','o'),
    name = ~year,
    marker = list(size = 10),
    type = 'scatter',
    mode = 'lines+markers'
  )

q <- plot_ly(palma, x = "Coeff. di Palma", y = ~value, alpha = 0.7) %>%
  add_trace(
    symbol = ~year,
    symbols = c('circle','x','o'),
    name = ~year,
    marker = list(size = 10),
    type = 'scatter',
    mode = 'lines+markers'
  )

r <- plot_ly(S, x = "S80/S20", y = ~value, alpha = 0.7) %>%
  add_trace(
    symbol = ~year,
    symbols = c('circle','x','o'),
    name = ~year,
    marker = list(size = 10),
    type = 'scatter',
    mode = 'lines+markers'
  )

# Combine subplots with adjusted spacing
subplot(p, q, r, spacing = 0.1) %>%
  layout(
    title = "Inequality Metrics (2018-2020)",
    showlegend = TRUE
  )

Quick Notes:

  • The pipe operator (%>%) makes the code cleaner and easier to follow—this is a standard practice in R workflows.
  • If you need ultra-precise cm-based spacing, adjust the overall plot width (e.g., layout(width = 1200)) and tweak the spacing value until you get the gap size you want.

内容的提问来源于stack exchange,提问作者Anna

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.11 07:42:34