我很習慣使用 tidyverse 和 ggplot。我正在嘗試生成一個互動式圖形以使用 flexdashboard 進行部署。因此,我試圖在 plotly 中生成我常用的 ggplots。
假設我有以下資料框:
data.frame(id = c(1:5),
product = c("product1","product2","product1","product3","product2"),
variable = c("var1","var1","var3","var2","var1"),
price = c(100,120,140,90,80))
有輸出:
id product variable price
1 1 product1 var1 100
2 2 product2 var1 120
3 3 product1 var3 140
4 4 product3 var2 90
5 5 product2 var1 80
如果我想在圖上顯示所有這些,我會在 ggplot 中執行以下操作:
library(tidyverse)
library(hrbrthemes)
data.frame(id = c(1:5),
product = c("product1","product2","product1","product3","product2"),
variable = c("var1","var1","var3","var2","var1"),
price = c(100,120,140,90,80)) %>%
ggplot(aes(x = id, y = price, color = variable))
geom_point()
facet_wrap(~product)
theme_ft_rc()
哪個會產生:

我知道我可以通過使用該subplot()
函式在 plotly 中實作類似的功能。問題是我有 14-28 個類別可以繪制為方面。據我了解,這意味著我必須制作 14-28 個圖,然后將它們排列在網格中。這似乎有點乏味,我想知道是否有更有效的方法來實作這一點,例如 ggplot 中的 facet 選項。我還在另一篇文章中得到了一段代碼:
library(plotly)
dataframe <- data.frame(id = c(1:5),
product = c("product1","product2","product1","product3","product2"),
variable = c("var1","var1","var3","var2","var1"),
price = c(100,120,140,90,80)) %>%
pivot_wider(names_from = "product", values_from = "price")
vars <- setdiff(names(dataframe),"id")
plots <- lapply(vars, function(var){
plot_ly(dataframe, x = ~id, color =~variable, y = as.formula(paste0("~",var))) %>%
add_bars(name = var)
})
subplot(plots, nrows = length(plots), shareX = TRUE, titleX = FALSE)
其中產生:

并且需要對樣本框中pivot_wider()的product列使用 tidyr 的函式。但是,我的真實列包含數字和字符,使用上述示例代碼時會產生錯誤。變數列也以一種奇怪的方式顯示。是否有解決此問題的方法,或者是真正為每個情節手動撰寫代碼的最佳方法?
uj5u.com熱心網友回復:
根據您的第一個示例(我剛剛洗掉了您的主題樣式),它的作業方式是這樣的。
df <- data.frame(
id = c(1:5),
product = c("product1","product2","product1","product3","product2"),
variable = c("var1","var1","var3","var2","var1"),
price = c(100,120,140,90,80)
)
plot <- ggplot(df, aes(x = id, y = price, color = variable))
geom_point()
facet_wrap(~product)
ggplotly(plot)

唯一的區別是我沒有使用 %>% 鏈接,因為當我在下面嘗試時,它似乎會引發錯誤:
data.frame(
id = c(1:5),
product = c("product1","product2","product1","product3","product2"),
variable = c("var1","var1","var3","var2","var1"),
price = c(100,120,140,90,80)
) %>% ggplot(aes(x = id, y = price, color = variable))
geom_point()
facet_wrap(~product) %>% ggplotly()
# Error in UseMethod("ggplotly", p) :
# no applicable method for 'ggplotly' applied to an object of class "c('FacetWrap', 'Facet', 'ggproto', 'gg')"
帶有自定義工具提示的擴展示例
您可以隨心所欲地制作它,我添加了價格格式,并為了它的樂趣將產品和變陣列合為工具提示中的一行。
custom_tooltip <- paste0("ID: ", df$id, "\n", "Product: ", df$product, " (", df$variable, ")\n", "Sold for: £ ", df$price)
plot <- ggplot(df, aes(x = id, y = price, color = variable))
geom_point(aes(text = custom_tooltip))
facet_wrap(~product)
ggplotly(plot, tooltip = c("text"))

轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/376606.html
標籤:r ggplot2 情节地 弹性仪表板 ggplotly
