ggplot2:为geom_line添加点

the*_*ega 9 r ggplot2

我在ggplot2中有一个线图,我想为每个数据行添加点(=形状)以清楚地识别它.我不(!)在每个数据点都需要一个形状/点,而是一些值就足够了.请参阅以下示例:

library(ggplot2)
library(data.table)
d=data.table(x=seq(0, 100, by=0.1), y=seq(0,1000)))
ggplot(d, aes(x=x, y=y))+geom_line()
ggplot(d, aes(x=x, y=y))+geom_line()+geom_point()
Run Code Online (Sandbox Code Playgroud)

仅限线路 增加点数

由于样本数量巨大,形状不再可见,而是相互透支.我只需要其中的一些,也许等距间距看起来最好,但我对任何其他解决方案持开放态度.

emh*_*art 11

您还可以添加一些点,只需使用索引来细化数据.

library(ggplot2)
library(data.table)
d=data.table(x=seq(0, 100, by=0.1), y=seq(0,1000))
ggplot(d, aes(x=x, y=y))+geom_line()
#Change the length parameter for fewer or more points
thinned <- floor(seq(from=1,to=dim(d)[1],length=70))
ggplot(d, aes(x=x, y=y))+geom_line()+geom_point(data=d[thinned,],aes(x=x,y=y))
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述


Sve*_*ein 5

您可以用某些分位数绘制点quantile.例如,以下序列生成十分位数.

quantile(rnorm(100), probs = seq(0, 1, .1))
#         0%         10%         20%         30%         40%         50%         60%         70%         80%         90%        100% 
#-2.43934306 -1.17208001 -0.91497203 -0.69489868 -0.46306926 -0.24133438 -0.03434118  0.39989589  0.72331902  1.06402664  2.02892420 

library(ggplot2)
library(data.table)
d <- data.table(x = seq(0, 100, by=0.1), y = seq(0,1000))

ggplot(d, aes(x=x, y=y))+
geom_line()+
geom_point(aes(x = quantile(x, probs = seq(0, 1, .1)),
               y = quantile(y, probs = seq(0, 1, .1))))
Run Code Online (Sandbox Code Playgroud)

以十分位数绘制点


Bar*_*Bar 5

只是想添加一个data.table也可以处理分组数据的解决方案:

library(ggplot2)
library(data.table)

# Creates data from the Weibull distribution
weib_dt <- function(x = seq(0, 4.0, 0.01), w_shape = 1, w_scale = 1) {
  y = dweibull(x, shape = w_shape, scale = w_scale)
  data.table("shape" = as.factor(w_shape), "scale" = as.factor(w_scale), "x" = x, "y" = y)
}

dt_a <- weib_dt(w_shape = 0.5)
dt_b <- weib_dt(w_shape = 1.0)
dt_c <- weib_dt(w_shape = 2.0)
# Bind multiple Weibull samples together, created from different parametrizations
dt_merged <- rbindlist(list(dt_a, dt_b, dt_c))

# Create the plot, using all the points for the lines, and only 9 points per group for the points.
ggplot(dt_merged, aes(x, y, group=shape, color=shape)) + 
  coord_cartesian(ylim = c(0, 1.5)) +
  geom_line() +
  geom_point(data=dt_merged[, .SD[floor(seq(1, .N, length=9))], by=shape], 
             aes(x, y, group = shape,  color = shape, shape = shape))
Run Code Online (Sandbox Code Playgroud)

这里的技巧是将seqas 与上面建议的解决方案一起使用,但这一次是在组内完成的(使用.SD)。请注意,当前.SD性能可能很差,dt[dt[, ..., by =shape]$V1]如果速度很慢,您可以使用更详细的内容。

这将创建以下输出:

威布尔图