如何结合重复因子使用ggplot2绘制ggplot_dumbbell图?
Hey there! Let's get that dumbbell plot sorted out with your repeated phi values and grouped Type categories. First, I'll fill in the missing bits of your dataset to make it reproducible, then walk through the plotting step by step.
Step 1: Complete the Dataset
Your Type vector was cut off, so I've filled it in to match the length of your phi and W columns:
df_senPhi <- structure(list( phi = c(0.1, 0.15, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 0.9, 1), W = c(7833625.7334, 8291583.0188, 8762978.0131, 8169317.158, 8460793.8918, 8765222.8718, 8266025.5499, 8311199.2075, 8265304.816, 8289392.5799, 8273733.0523, 8284554.5615), Type = c("A, B, C", "A, B, C", "A, B, C", "D, E", "D, E", "D, E", "F, G", "F, G", "H, I", "H, I", "I, J", "I, J") ), class = "data.frame", row.names = c(NA, -12L))
Step 2: Build the Core Dumbbell Plot
The key here is treating phi as a factor so repeated values sit on the same y-axis line, then using Type to distinguish the endpoints. Here's the working code:
library(ggplot2) library(ggalt) theme_set(theme_classic()) ggplot(df_senPhi, aes(x = W, y = factor(phi))) + # Draw the dumbbell connectors and colored endpoints geom_dumbbell(aes(color = Type), size = 1.5, # Thickness of the connecting line point.size = 3, # Size of the endpoint dots colour_x = "gray50") # Neutral color for the connecting line + # Add clear labels and a distinct color palette scale_color_brewer(palette = "Set1") + labs(x = "W Value", y = "Phi", color = "Group Type") + # Tweak theme for better readability theme(axis.text.y = element_text(size = 10), legend.position = "bottom")
Step 3: Optional Accessibility & Customization
If you want to differentiate groups by shape and color (great for colorblind viewers), modify the aes() to include shape = Type:
ggplot(df_senPhi, aes(x = W, y = factor(phi))) + geom_dumbbell(aes(color = Type, shape = Type), size = 1.5, point.size = 3, colour_x = "gray50") + scale_color_brewer(palette = "Set1") + scale_shape_manual(values = c(16, 17, 18, 19, 20, 21)) + labs(x = "W Value", y = "Phi", color = "Group Type", shape = "Group Type") + theme(axis.text.y = element_text(size = 10), legend.position = "bottom")
Quick Tips
- Double-check that every row has a clear
Typeassignment—this is how the plot pairs endpoints for the samephi - If a
phivalue only has one correspondingW, the plot will show a single dot instead of a dumbbell - Adjust
size,point.size, or color palettes to match your visualization style needs
内容的提问来源于stack exchange,提问作者anup
相关产品推荐
相关产品推荐

