R ggplotly()和颜色注释-如何做到?

问题描述 投票:1回答:1

我正在尝试从ggplot复制图表,并从Plotly中将鼠标悬停点添加到功能中,但是它会剥去注释,并且已经尝试了所有方法来获得相同的视图,但没有成功。

library("ggplot2")
library("plotly")
test_data <- data.frame(A = c(1,5,7,4,2),
                        B = c(3,3,6,8,4))

my_days <- as.Date(c("2010-01-01", "2010-02-01",
                      "2010-03-01", "2010- 4-01",
                      "2010-05-01"))

df <- data.frame(test_data, my_days)

# Anotate Box
s_1 <- unique(min(df$my_days))
s_2 <- unique(max(df$my_days))

target <- 1

plot_out <- df %>% 
  group_by(my_days) %>% 
  summarise(prop = sum(A / B)) %>% 
  ggplot(aes(x =my_days, y = prop)) +
  geom_line(color = "purple") + 
  annotate("rect", xmin = s_1, xmax = s_2, ymin = -Inf, ymax = target, alpha = .2, fill = "red") +
  annotate("rect", xmin = s_1, xmax = s_2, ymin = target, ymax = Inf, alpha = .2, fill = "green")

plot_out # Plot with Colour 

ggplotly(plot_out) # This gives the hover info points , but removes the annotates 

Ggplot with annotations but no hover points which is why I pass through Plotly

Plotly output with info points but removed the annotates.

ggplot2 ggplotly annotate
1个回答
0
投票
不是ggplotly解决方案,而是plotly解决方案。 (;至少在我看来,如果要制作ggplot的快速交互式版本,ggplotly很好。但是,ggplotly仍然有很多问题,无法转换每个ggplot。请尝试:

library("ggplot2") library("plotly") test_data <- data.frame( A = c(1, 5, 7, 4, 2), B = c(3, 3, 6, 8, 4) ) my_days <- as.Date(c( "2010-01-01", "2010-02-01", "2010-03-01", "2010- 4-01", "2010-05-01" )) df <- data.frame(test_data, my_days) # Anotate Box s_1 <- unique(min(df$my_days)) s_2 <- unique(max(df$my_days)) target <- 1 p <- df %>% group_by(my_days) %>% summarise(prop = sum(A / B)) %>% plot_ly(x = ~my_days, y = ~prop) %>% add_lines( line = list(color = "purple"), hoverinfo = "text", text = ~ paste0( "mydays: ", my_days, "\n", "prop: ", round(prop, 7) )) %>% # Add the rectangles and set x-axis as in ggplot layout( xaxis = list( type = "date", tickformat = "%b", nticks = 5 ), shapes = list( list( type = "rect", fillcolor = "red", opacity = 0.2, x0 = s_1, x1 = s_2, xref = "x", y0 = -Inf, y1 = target, yref = "y" ), list( type = "rect", fillcolor = "green", opacity = 0.2, x0 = s_1, x1 = s_2, xref = "x", # Setting y1 to Inf results in a yaxis which spans up to 2.5. So I chose 1.8 to mimic the ggplot y0 = target, y1 = 1.8, yref = "y" ) ) ) p

enter image description here

reprex package(v0.3.0)在2020-04-05创建

© www.soinside.com 2019 - 2024. All rights reserved.