r语言 - 带有工具提示的 ggplotly 在使用 geom_rect() 时出现问题



我正在尝试在ggplotly图中绘制一些数据。 x 轴包含日期。Ggplotly 不适用于日期,因为当我将鼠标悬停在一个点上时,日期显示为数字。 我通过设置如下所示的工具提示来解决此问题。

一些示例数据:

x <- data.frame(Date = as.Date(seq(Sys.Date(), Sys.Date() + 29, by = "days")), Amount = seq(-10000, 19000, by = 1000),
stringsAsFactors = FALSE)

剧情:

ggplotly(ggplot(x, aes(x = Date, y = Amount, group = 1, text = paste("Date: ", Date, "<br>Amount: ", Amount))) + geom_line() + geom_point() 
, tooltip = "text")

现在我想使用 geom_rect(( 根据 y 轴的值获取一些背景颜色。这给我带来了问题,因为矩形似乎放在 geom_line(( 的顶部。此外,矩形也由 ggplotly 标记,我也不想。 这是我尝试的代码(当我不使用自定义工具提示时,背景着色工作正常,但随后标签中的日期出现问题(:

ggplotly(ggplot(x, aes(x = Date, y = Amount, group = 1, text = paste("Date: ", Date, "<br>Amount: ", Amount))) + geom_line() + geom_point() 
+
geom_rect(aes(xmin = as.Date(Sys.Date()),
xmax = as.Date(Sys.Date() + 30),
ymin = 10000, ymax = max(max(x$Amount) + 1000, 11000), fill = "1")) +
geom_rect(aes(xmin = as.Date(Sys.Date()),
xmax = as.Date(Sys.Date() + 30),
ymin = 0, ymax = 10000, fill = "2")) +
geom_rect(aes(xmin = as.Date(Sys.Date()),
xmax = as.Date(Sys.Date() + 30),
ymin = min(min(x$Amount) - 1000, 0), ymax = 0, fill = "3"))
+
scale_fill_manual(values = alpha(c("green", "orange", "red"), 0.2))
, tooltip = "text")

结果

任何帮助将不胜感激,谢谢!

编辑:

以下代码导致工作 geom_rect((:

ggplotly(ggplot(x, aes(x = Date, y = Amount)) + geom_line() + geom_point() 
+
geom_rect(aes(xmin = as.Date(Sys.Date()),
xmax = as.Date(Sys.Date() + 30),
ymin = 10000, ymax = max(max(x$Amount) + 1000, 11000), fill = "1")) +
geom_rect(aes(xmin = as.Date(Sys.Date()),
xmax = as.Date(Sys.Date() + 30),
ymin = 0, ymax = 10000, fill = "2")) +
geom_rect(aes(xmin = as.Date(Sys.Date()),
xmax = as.Date(Sys.Date() + 30),
ymin = min(min(x$Amount) - 1000, 0), ymax = 0, fill = "3"))
+
scale_fill_manual(values = alpha(c("green", "orange", "red"), 0.2)))

结果

你可以试试这个:

ggplotly(ggplot() +
geom_rect(data = x, aes(xmin = as.Date(Sys.Date()),
xmax = as.Date(Sys.Date() + 30),
ymin = 10000, ymax = max(max(x$Amount) + 1000, 11000), fill = "1")) +
geom_rect(data = x, aes(xmin = as.Date(Sys.Date()),
xmax = as.Date(Sys.Date() + 30),
ymin = 0, ymax = 10000, fill = "2")) +
geom_rect(data = x, aes(xmin = as.Date(Sys.Date()),
xmax = as.Date(Sys.Date() + 30),
ymin = min(min(x$Amount) - 1000, 0), ymax = 0, fill = "3")) + 
geom_line(data = x, aes(x = Date, y = Amount, group = 1, text = paste("Date: ", Date, "<br>Amount: ", Amount))) + 
geom_point(data = x, aes(x = Date, y = Amount, text = paste("Date: ", Date, "<br>Amount: ", Amount))) +
scale_fill_manual(values = alpha(c("green", "orange", "red"), 0.2))
, tooltip = "text")

相关内容

  • 没有找到相关文章