R Plotly与Shiny可视化求助:异常边距及双X轴设置
Hey there! Let's work through your two Plotly + Shiny visualization issues step by step. I’ve reviewed your code and identified key tweaks to fix both the margin problem and add dual X-axes.
1. Fix Excessive Top/Bottom Margins for Large Y-Axis Datasets
First, I spotted a typo in your yaxis configuration: you used categoryarray = ~qt, but your data frame doesn’t have a qt column—this should be ~y instead! This mistake could throw off Y-axis rendering and contribute to weird spacing. Additionally, fixed top/bottom margins (t=100, b=50) don’t scale well when you have 40+ Y-axis items. We’ll adjust these to be dynamic based on the number of rows in your data, plus tweak annotation font size to avoid layout miscalculations.
2. Add X-Axis to Both Top and Bottom of the Chart
To display the X-axis on both the top and bottom, we’ll add a second X-axis (xaxis2) that overlays the primary X-axis and sits at the top. We’ll mirror the primary X-axis settings to keep styling consistent.
Full Revised Code
y <- c("q1", "q2", "q3", "q4", "q5", "q6", "q7") x1 <- c(20, 10, 15, 15, 20, 10, 15) x2 <- c(10, 20, 20, 10, 10, 30, 10) x3 <- c(10, 10, 5, 10, 10, 5, 5) x4 <- c(20, 25, 25, 35, 55, 40, 35) x5 <- c(40, 35, 35, 30, 5, 15, 35) num <- c(1,3,5,6,7,2,4) df <- data.frame(y, x1, x2, x3, x4, x5, num) plot_ly(df[order(-xtfrm(df$num)),]) %>% add_trace(x = ~x1, y = ~y, marker = list(color = 'rgb(202,0,32)'), type = 'bar', orientation = 'h') %>% add_trace(x = ~x2, y = ~y, marker = list(color = 'rgb(244,165,130)'), type = 'bar', orientation = 'h') %>% add_trace(x = ~x3, y = ~y, marker = list(color = 'rgb(223,223,223)'), type = 'bar', orientation = 'h') %>% add_trace(x = ~x4, y = ~y, marker = list(color = 'rgb(146,197,222)'), type = 'bar', orientation = 'h') %>% add_trace(x = ~x5, y = ~y, marker = list(color = 'rgb(5,113,176)'), type = 'bar', orientation = 'h') %>% layout( title="mytitle", xaxis = list( title = "", showticklabels = TRUE, zeroline = FALSE, domain = c(0.15, 1), anchor = 'y' # Link primary X-axis to main Y-axis ), xaxis2 = list( title = "", showticklabels = TRUE, zeroline = FALSE, domain = c(0.15, 1), overlaying = 'x', # Overlay on primary X-axis side = 'top' # Position at the top of the chart ), yaxis = list( title = "", showticklabels = FALSE, zeroline = FALSE, categoryorder = 'array', categoryarray = ~y # Fixed typo here ), barmode = 'relative', paper_bgcolor = 'rgb(248, 248, 255)', plot_bgcolor = 'rgb(248, 248, 255)', autosize=T, # Dynamic margins: shrink top/bottom when >40 Y-axis items margin = list( l = 150, r = 10, t = ifelse(nrow(df) > 40, 50, 100), b = ifelse(nrow(df) > 40, 30, 50), pad=4 ), showlegend=F ) %>% # Adjusted font size to prevent layout glitches add_annotations( xref = 'paper', yref = 'y', x = 0.14, y = df$y, xanchor = 'right', text = df$y, font = list(family = 'Arial', size = 10, color = 'rgb(67, 67, 67)'), showarrow = FALSE, align = 'right' )
内容的提问来源于stack exchange,提问作者dorayin

