如何添加线以连接 R 中多个箱线图中的某些数据点?

我正在尝试创建一个类似于 this 的图表,其中每个箱线图的一个特定数据点通过一条红线连接到下一个。

我当前的代码是:

p <- ggplot(melt_opt_base,aes(factor(variable),value))
p + geom_boxplot() + labs(x = "Variable",y = "Value")

当前图形看起来像 this。假设要连接的数据点是:

points = c(0,0.1,0.2,0.3,0.3)

有谁知道我如何在九个相邻的箱线图中添加一条连接这些点的线,使其看起来像 this instead

zppeipei 回答:如何添加线以连接 R 中多个箱线图中的某些数据点?

这可以像这样实现:

  1. 使用您的类别和点值制作数据框
  2. 将此数据帧作为数据传递给 geom_line 和或 geom_point

使用 ggplot2::diamonds 作为示例数据:

library(ggplot2)

points <- aggregate(price ~ cut,FUN = mean,data = diamonds)

points
#>         cut    price
#> 1      Fair 4358.758
#> 2      Good 3928.864
#> 3 Very Good 3981.760
#> 4   Premium 4584.258
#> 5     Ideal 3457.542

ggplot(diamonds,aes(cut,price)) + 
  geom_boxplot() +
  geom_point(data = points,color = "red") +
  geom_line(data = points,aes(group = 1),color = "red")

本文链接:https://www.f2er.com/45541.html

大家都在问