如何将ggplot转换为plot_ly?

时间:2019-10-08 22:04:54

标签: r ggplot2 shiny plotly ggplotly

我正在尝试创建一个包含仪表盘的Shiny Dashboard。 Plotly是一个很棒的软件包,可以为用户提供出色的可视化和交互性。

我知道将ggplot转换为plotly的最佳方法是使用ggplotly()函数。但是,当我使用ggplotly时,我面临着仪表板中图的大小和外观方面的问题。之前,我曾问过一个问题(ggplotly not working properly when number are facets are more ),并且我尝试了一个阴谋的社区来克服这个问题,但是我认为这是一个错误。

最后,我已经确定要手动将ggplot转换为plot_ly。但是,在这样做的同时,我面临一些障碍,而且我不确定自己在做的是正确的还是最简单的方法。

我用来生成ggplot的代码是

Source_Data_dupli <-
data.frame(
key = c(1, 1, 1, 2, 2, 2, 3, 3, 3,4,4,5,5,6,7),
Product_Name = c(
"Table",
"Table",
"Chair",
"Table",
"Bed",
"Bed",
"Sofa",
"Chair",
"Sofa",
"Table",
"Bed",
"Chair",
"Table",
"Bed",
"Bed"
 ),
Product_desc = c("XX", "XXXX", "YY", "X", "Z", "ZZZ", "A", "Y", 
"A","Y","XX", "XXXX", "YY", "X", "Z"),
sd =c(0.1,0.3,0.4,0.5,0.6,0.7,0.7,0.8,0.5,0.9,0.5,0.2,0.3,0.4,0.5),
Cost = c(1, 2, 3, 4, 2, 3, 4, 5, 6, 7,6,8,9,12,34)
)

################ ggplot ####################

Source_Data %>% 
ggplot(aes(Product_Name, Cost, fill = Product_desc)) + 
geom_col(position = position_dodge2(width = .9, preserve = "single")) + 
geom_errorbar(aes(ymin=Cost-sd, ymax=Cost+sd), position = 
position_dodge2(width = .9, preserve = "single", padding = .5)) +
geom_text(aes(y=Cost+sd, label=Cost), position = position_dodge2(width=.9), 
vjust = -1) +
facet_wrap(~key, scales = "free_x", strip.position = "bottom") +
theme(strip.placement = "outside") + 
theme_bw()

感谢Advance的帮助。

大卫

0 个答案:

没有答案