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?
Asked
Active
Viewed 175 times
0

Ronak Shah
- 377,200
- 20
- 156
- 213

Our
- 986
- 12
- 22
1 Answers
1
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))
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())
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))

chemdork123
- 12,369
- 2
- 16
- 32
-
thanks for the answer. I would also appreciate an answer to this question (https://stackoverflow.com/questions/66754302/accessing-the-values-of-the-reduced-dataset-after-facet-grid-in-ggplot) if you have one – Our Mar 22 '21 at 21:49