R语言 使用geom_line扩展线长度

u5rb5r59  于 2023-01-06  发布在  其他
关注(0)|答案(2)|浏览(198)

我想在一个图形上表示三条线,这些线上覆盖着我在判别函数分析中使用的数据点。根据我的分析,我有两个点落在每条线上,我想表示这三条线。这些线表示分类方案的概率等高线,我如何得到线上的点与我的问题无关。然而,我希望直线比定义它们的点延伸得更远。

df <- 
  data.frame(Prob = rep(c("5", "50", "95"), each=2),
                 Wing = rep(c(107,116), 3),
                 Bill = c(36.92055, 36.12167, 31.66012, 30.86124, 26.39968, 25.6008))

ggplot()+
   geom_line(data=df, aes(x=Bill, y=Wing, group=Prob, color=Prob))

上面的df是我的点的 Dataframe ,从这些点可以构造出三条线。我希望这些线从y=105to y=125开始延伸。谢谢!

yqkkidmi

yqkkidmi1#

可能还有更惯用的方法来做这件事,但这是一种完成它的方法。
简而言之,您可以快速计算连接直线的线性公式,即y = mx+c

df_withFormula <- df |>
  group_by(Prob) |>
  #This mutate command will create the needed slope and intercept for the geom_abline command in the plotting stage.
  mutate(increaseBill = Bill - lag(Bill),
         increaseWing = Wing - lag(Wing),
         slope = increaseWing/increaseBill,
         intercept = Wing - slope*Bill)
# The increaseBill, increaseWing and slope could all be combined into one calculation but I thought it was easier to understand this way.

ggplot(df_withFormula, aes(Bill, Wing, color = Prob)) +
  #Add in this just so it has something to plot ontop of. You could remove this and instead manually define all the limits (expand_limits would work).
  geom_point() +
  #This plots the three lines. The rows with NA are automatically ignored. More explicit handling of the NA could be done in the data prep stage
  geom_abline(aes(slope = slope, intercept = intercept, color = Prob)) +
  #This is the crucial part it lets you define what the range is for the plot window. As ablines are infite you can define whatever limits you want.
  expand_limits(y = c(105,125))

希望这能帮助你得到你想要的图表。
这在很大程度上取决于数据的结构,但可以对其进行更改以适应不同的形状。

esbemjvw

esbemjvw2#

类似于@James的方法,我根据给定数据计算斜率和截距,并使用geom_abline绘制直线,但使用

  • summarise而不是mutate,以删除NA
  • geom_blank代替geom_point,以便只显示线而不显示点(注:拥有另一个geom对于设置scale或数据范围以及显示行至关重要)。
library(dplyr)
library(ggplot2)

df_line <- df |> 
  group_by(Prob) |> 
  summarise(slope = diff(Wing) / diff(Bill),
            intercept = first(Wing) - slope * first(Bill))

ggplot(df, aes(x = Bill, y = Wing)) +
  geom_blank() +
  geom_abline(data = df_line, aes(slope = slope, intercept = intercept, color = Prob)) +
  scale_y_continuous(limits = c(105, 125))

相关问题