Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
554 views
in Technique[技术] by (71.8m points)

r - date format in tooltip of ggplotly

I am using ggplotly to show an interactive time-series plot. The x axis is in date format, yet the hover tool tip in plotly is converting the date format to a numeric (screenshot attached). Any ideas on how to get the date to show as a proper date in the tooltip?

Below is a short piece of the code:

 output$ggplot <- renderPlotly({

plotbycity<-df_postgres %>% group_by(city, date, bedroooms) %>%
  filter(city %in% input$checkGroup & bedroooms==input$radio) %>%
  summarise(count=n(),rent=median(rent)) %>%
  ungroup() 

plotbycity$date<-as.Date(plotbycity$date)


# Error handling
plotbycity<-plotbycity[!is.na(plotbycity$city),]
if (is.null(plotbycity)) return(NULL)

#plotbycity<-ungroup(plotbycity)
#dat <- dat[c("rent", "bedroooms", "date", "City")]
#dat <- melt(dat,id.vars=c("date", "City", "bedroooms"),na.rm=TRUE)   #

# draw the line plot using ggplot
 gg <-ggplot(plotbycity, aes(x = date, y = rent, group = city, color = city,
                             text = paste('obs: ', count))) +
  geom_line() +
  ggtitle("Monthly Rents")
#   #theme_hc(bgcolor = "darkunica") +
#   #scale_fill_hc("darkunica")
 
 p <- ggplotly(gg, tooltip = c("x", "y", "text"))

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

If you use just text in your tooltip, you can render a more complex tooltip by using the text element you pass to ggplot. You just need to call as.Date and use some <br> html tags as follows:

# draw the line plot using ggplot
gg <-ggplot(plotbycity, aes(x = date, y = rent, group = city, color = city,
    text = paste('Rent ($):', rent,
                 '<br>Date: ', as.Date(date),
                 '<br>Obs: ', count))) +
    geom_line() +
    ggtitle("Monthly Rents")

p <- ggplotly(gg, tooltip = c("text"))

Hope that helps!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.9k users

...