如何用gghighlight随机选择其中一行并突出显示它? [英] How to randomly choose one of the lines with gghighlight and highlight it?
问题描述
在此处中使用示例我有一堆线,如果数据点根据数据表中的 ID
列相互连接以形成一条线,该如何随机选择其中的一条?
Using the example in here, if I have a bunch of line, how can I randomly choose one of them if the data points connected to each other to form a line according to, say ID
, column in the data table?
推荐答案
您可以使用 sample()
函数随机获取一个值.如果您的数据框称为 df
,则我想在您的 gghighlight()
行中使用以下内容:
You can use the sample()
function to grab a value at random. If your dataframe is called df
, I'd think something like this for your gghighlight()
line:
# your plot code = p
p + gghighlight(ID == sample(unique(df$ID),1))
这将随机突出显示 df $ ID
中唯一值向量中的一个值.重要的是要注意,如果您希望它总是 是随机的,并且您事先在脚本的其他位置设置了任何随机种子,则需要重置随机种子.这些选项中的任何一个都是执行此操作的好方法:
That would highlight one value from the vector of unique values in df$ID
at random. It's important to note that if you want this to always be random and you have elsewhere in a script beforehand set any random seed, you will need to reset the random seed. Either of these options would be a good way to do that:
set.seed(NULL)
set.seed(Sys.time())
在您链接的 gghighlight
的示例中,这是添加到该脚本中的方法,以确保您随机选择一行(因为数据是由 set.seed一致生成的)(2)
在代码开头):
In the example from gghighlight
you linked, this is how you would add to that script to ensure that you picked a line at random (since the data is generated consistently by set.seed(2)
in the beginning of the code):
set.seed(NULL)
ggplot(d) +
geom_line(aes(idx, value, colour = type)) +
gghighlight(sample(type==unique(d$type),1))
这篇关于如何用gghighlight随机选择其中一行并突出显示它?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!