Hello there,
I am using plotly with ggplot2, and I would like to change the format of the tooltip.
I am using the text aesthetic, as suggested by https://plot.ly/ggplot2/interactive-tooltip/#custom-tooltip.
However, I have noticed that adding a text aesthetic may change the grouping, although the text aesthetic is said to be ignored in ggplot2.
This has an impact on geoms.
For example,
times ← seq(ISOdate(2017,1,1, tz = “”), by = “month”, length.out = 12)
values ← rnorm(12, mean = 50, sd = 10)
stats = rep(c(“a”, “b”, “c”), times = 4)
df ← data.frame(time = times, stat = stats, value = values)
df
p ← ggplot(df, aes(x = time,
y = value,
color = stat
)) +
geom_point() +
geom_line()
ggplotly(p, tooltip = “time”)
The tooltip is shown in full format %Y-%m-%d %H:%M:%S
I want to change the format to %Y-%m-%d, without changing the real time value.
So, as suggested, I add a text aesthetic.
p ← ggplot(df, aes(x = time,
y = value,
color = stat,
text = format(time, “%Y-%m-%d”)
)) +
geom_point() +
geom_line()ggplotly(p, tooltip = “text”)
However, now the groupings have changed, and the geom_line() draws nothing because all groups only have a single element.
This is not limited to dates. However there should be some grouping to make the issue visible.
Consider this simple data frame
x ← c(1.001, 2.002, 3.003)
y ← c(1, 2, 3)
z ← c(“a”,“a”,“b”)
df ← data.frame(x = x, y = y, z = z)
and the simple plot
p ← ggplot(df, aes(x,
y,
color = z)) +
geom_line() +
geom_point()ggplotly(p, tooltip = “x”)
the first two points belong to group “a”, the third point belongs to group “b”.
As there are two points in group “a”, the geom_line() draws a single line segment.
I want to round the x values in the tooltip, so I add the text aesthetic (and a label) :
p ← ggplot(df, aes(x,
y,
color = z,
text=paste(“x_rounded:”, round(x)))) +
geom_line() +
geom_point()ggplotly(p, tooltip = “text”)
Apparently, the line segment disappears.
Note that the line segment is drawn when I alter the text aesthetic to round(x).
Can I work around this issue ?
Package versions :
packageVersion(“ggplot2”)
[1] ‘2.2.1.9000’
packageVersion(“plotly”)
[1] ‘4.7.1’
Thank you
Bart