按条件在Plotly r中选择颜色或标记符号

时间:2018-03-22 23:12:39

标签: r plotly scatter-plot r-plotly

terraform destroy

我有上面的数据(简化)。我使用散点图绘制了这个图,其中Id为X轴,值为Y轴。现在基于时间列,我希望Id字段的最新条目具有特定的形状/符号。我怎么能用plot-ly和r?

来做到这一点

1 个答案:

答案 0 :(得分:0)

I would add a column to flag the last entry, then use that column as an aesthetic .

For example, in ggplot:

df %>%
    group_by(Id) %>%
    mutate(
        rowNo = 1:n(),
        isLast = factor(ifelse(rowNo == n(), 1, 0))) %>%
    ggplot(aes(x = Id, y = Value, shape = isLast)) + geom_point()

enter image description here

And similarly for plot_ly.

df %>%
    group_by(Id) %>%
    mutate(
        rowNo = 1:n(),
        isLast = factor(ifelse(rowNo == n(), 1, 0))) %>%
    plot_ly(x = ~Id, y = ~Value, symbol = ~isLast)

Sample data

df <- read.table(text =
    "Id  Time Value
1 A  1
2 B 10
2 C  3
2 D  6
3 E  2
4 F  9
4 G  4
4 H 17", header = T)