R-plotly子图仅显示底部图:复现mtcars数据缩放子图遇问题
Fixing Scaled Subplots with mtcars and Plotly 4.9.0
Let's break down what's going wrong and how to fix it so your am==0 points show up in the top subplot as expected.
The Root Issue
When you use as.integer(factor(am)), R's default factor ordering turns am=0 into 1 and am=1 into 2—that part is correct. The problem likely stems from either:
- Ambiguous subplot axis mapping in Plotly 4.9.0 (without explicit domain settings, subplots might render in an unexpected order)
- Using a continuous color scale for
am(since it's numeric) instead of discrete colors, which makes it harder to verify group placement - Missing explicit layout controls to anchor each subplot to its intended position
Solution 1: Explicit Subplot Creation (Most Intuitive)
Split your data by am first, create separate plots for each group, then combine them. This eliminates confusion about axis mapping:
library(plotly) library(dplyr) # Split data into automatic (am=0) and manual (am=1) groups mtcars_auto <- mtcars %>% filter(am == 0) mtcars_manual <- mtcars %>% filter(am == 1) # Create top subplot (am=0, automatic) p_top <- plot_ly(mtcars_auto, x = ~mpg, y = ~qsec, color = ~factor(am, labels = c("Automatic", "Manual")), type = "markers") %>% layout(yaxis = list(title = "qsec (Automatic)")) # Create bottom subplot (am=1, manual) p_bottom <- plot_ly(mtcars_manual, x = ~mpg, y = ~qsec, color = ~factor(am, labels = c("Automatic", "Manual")), type = "markers") %>% layout(yaxis = list(title = "qsec (Manual)")) # Combine subplots with shared X-axis, top-to-bottom order subplot(p_top, p_bottom, nrows = 2, shareX = TRUE, titleY = TRUE)
Solution 2: Pipe-Friendly Fix with Explicit Axis Domains
If you prefer keeping the single pipeline, fix the axis mapping and add explicit layout rules to enforce subplot positions:
library(plotly) library(dplyr) mtcars %>% # Directly map am to axis IDs (no factor ambiguity) mutate(axis_id = ifelse(am == 0, "y1", "y2")) %>% plot_ly(x = ~mpg, y = ~qsec, color = ~factor(am, labels = c("Automatic", "Manual")), yaxis = ~axis_id) %>% add_markers() %>% subplot(nrows = 2, shareX = TRUE) %>% # Define exact positions for each y-axis (top = y1, bottom = y2) layout( yaxis = list(domain = c(0.55, 1), title = "qsec (Automatic)"), yaxis2 = list(domain = c(0, 0.45), title = "qsec (Manual)") )
Key Fixes Explained
- Discrete Color Mapping: Converting
amto a factor (factor(am)) gives you distinct colors for each group, making it easy to confirm which points belong to which subplot. - Explicit Axis Domains: The
domainparameter inlayoutforcesy1(am=0) to occupy the top half of the plot andy2(am=1) to occupy the bottom half. - Clear Axis Mapping: Using
ifelseinstead ofas.integer(factor(am))removes any confusion about howamvalues map to axis IDs.
内容的提问来源于stack exchange,提问作者unamourdeswann
相关产品推荐
相关产品推荐

