You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何结合重复因子使用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 Type assignment—this is how the plot pairs endpoints for the same phi
  • If a phi value only has one corresponding W, 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 09:25:31