簡體   English   中英

應用 ggplotly() 后折線圖未連接

[英]Line graph not connected after applying ggplotly()

我有以下數據集

bike2 <- structure(list(dteday = c("2011-01", "2011-02", "2011-03", "2011-04", 
"2011-05", "2011-06", "2011-07", "2011-08", "2011-09", "2011-10", 
"2011-11", "2011-12", "2012-01", "2012-02", "2012-03", "2012-04", 
"2012-05", "2012-06", "2012-07", "2012-08", "2012-09", "2012-10", 
"2012-11", "2012-12"), cnt = c(38189L, 48215L, 63422L, 94870L, 
135821L, 143512L, 141341L, 136691L, 127418L, 123511L, 102167L, 
87323L, 96744L, 103137L, 164875L, 174224L, 195865L, 202830L, 
203607L, 214503L, 218573L, 198841L, 152664L, 123713L)), row.names = c(NA, 
-24L), class = c("tbl_df", "tbl", "data.frame"))

這是我目前擁有的圖表

a = ggplot(transform(bike2, year = substr(dteday, 1, 4)), 
       aes(x=dteday, y=cnt, group = 1, color = year))+
  geom_line(size = 1.2) + 
  labs(title = "Bike Rentals Per Month",
       x = "Month/Year",
       y = "Count") + 
  ggthemes::theme_solarized() +
  theme(axis.text.x=element_text(angle=45, hjust=1))

a

在此處輸入圖像描述

但是,當我嘗試將 ggplotly() 應用於圖形時,該線斷開連接。

plotly::ggplotly(a)

在此處輸入圖像描述

我該如何解決?

一個相關的問題指出,plotly 描述的系列與 ggplot 略有不同,導致一些類似這樣的翻譯問題。

一種解決方法是使用geom_segment明確說明您要為每個元素顯示的內容:

library(dplyr)
bike2 %>%
  mutate(dteday_next = lead(dteday),
         year = substr(dteday, 1, 4),
         cnt_next = lead(cnt)) %>%
ggplot(aes(x=dteday, xend = dteday_next,
           y=cnt, yend = cnt_next, color = year))+
  geom_segment() +
  labs(title = "Bike Rentals Per Month",
       x = "Month/Year",
       y = "Count") + 
  ggthemes::theme_solarized() +
  theme(axis.text.x=element_text(angle=45, hjust=1)) -> a
a

plotly::ggplotly(a)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM