如何在R语言中使用Plotly将环形图(Donut Charts)并排展示
Got it, to get your two donut charts arranged side-by-side using Plotly in R, the easiest and most flexible method is using Plotly's built-in subplot() function. Let's fix up your incomplete code and walk through the full implementation step by step:
Step 1: Load Required Packages
First, make sure you have all necessary packages loaded (note: dplyr is needed for data manipulation since you're using data_frame and mutate):
library(plotly) library(RColorBrewer) library(dplyr)
Step 2: Define Your Data & Color Scheme
We'll use your existing datasets and color setup, plus fix the factor ordering for your Score variable to match your color sequence:
# Your original datasets test <- data_frame(Score=c("Green","Green","Yellow","Yellow","Clear","Clear","Red","Red"), Lang=c(rep("Eng",4),rep("Esp",4))) test1 <- data_frame(Score=c("Green","Yellow","Yellow","Yellow","Clear","Clear","Red","Red"), Lang=c(rep("Eng",4),rep("Esp",4))) # Color configuration (matches your desired order) color_order <- c("Green","Clear","Yellow","Red") colors <- c("#31a354","#bdbdbd","#fec44f","#de2d26") # Convert Score to a factor to enforce order test <- test %>% mutate(Score = factor(Score, levels = color_order)) test1 <- test1 %>% mutate(Score = factor(Score, levels = color_order))
Step 3: Create Individual Donut Charts
First, we'll generate a donut chart for each dataset. Donut charts are just pie charts with a hole parameter set to a value between 0 and 1:
# Donut chart for test dataset p1 <- test %>% count(Score) %>% # Count occurrences of each Score plot_ly( type = "pie", labels = ~Score, values = ~n, hole = 0.6, # This makes it a donut instead of a solid pie colors = colors, categoryorder = "array", # Enforce our custom color/label order categoryarray = color_order, name = "Test Dataset" ) %>% layout(title = "Test Dataset", showlegend = FALSE) # Add title, hide duplicate legend # Donut chart for test1 dataset p2 <- test1 %>% count(Score) %>% plot_ly( type = "pie", labels = ~Score, values = ~n, hole = 0.6, colors = colors, categoryorder = "array", categoryarray = color_order, name = "Test1 Dataset" ) %>% layout(title = "Test1 Dataset")
Step 4: Arrange Charts Side-by-Side with subplot()
Finally, use subplot() to place the two charts in a single row (side-by-side). You can adjust margins and layout to tweak spacing:
# Combine plots into a side-by-side layout subplot(p1, p2, nrows = 1, margin = 0.05) %>% layout( title = "Side-by-Side Donut Charts", showlegend = TRUE, # Show one shared legend legend = list(x = 1.1, y = 0.5) # Position legend to the right of plots )
Key Notes:
- The
nrows = 1parameter tellssubplot()to arrange plots in a single row (usencols = 2if you prefer explicit column count). - The
marginparameter adjusts the spacing between plots to prevent overlapping titles/labels. - We set
showlegend = FALSEon one plot to avoid duplicate legends, then enable a shared legend in the final layout.
内容的提问来源于stack exchange,提问作者costebk08

