Plotly-R修改图例显示内容及调整子图间距技术求助
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
yearcolumn to each metric’s data frame (so we have a clear variable to link symbols to) - Set
symbol = ~yearandname = ~yearin 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 thespacingvalue until you get the gap size you want.
内容的提问来源于stack exchange,提问作者Anna

