I have barchart with dual-axis in order to visualize 3 numerical variables. All these work pretty nice in ggplot. However, when I convert ggplot to ggplotly, there are issues:
- in the legend, there are strange 1s (highlighted in yellow)
- in the hover, there are double values (highlighted in yellow)
- changes of hjust=0, vjust=-0.5 in geom_text are not reflected on the plot
Could anybody help me to adjust these issues?
df <- data.frame (model = c("A", "B", "C","D","E","F"),
share = c(12,20,15,9,60,20),
sale = c(16,25,18,14,67,28),
cost = c(14,19,28,24,57,28))
#set levels of model by cost
df$model <- factor(df$model, levels = arrange(df, desc(df$cost))$model)
library(tidyverse)
df_long <- df %>%
pivot_longer(
cols = -model
)
plt <- ggplot(df_long, aes(x = model, y= value, label=value))
geom_col(data = filter(df_long, name != "cost"), aes(fill=name), position = position_dodge())
scale_fill_manual(values = c("blue", "grey"))
geom_line(data = filter(df_long, name == "cost"), aes(color = name, group = 1), size = 1)
scale_color_manual(values = "red")
geom_text(data = filter(df_long, name == "cost"), size = 3,hjust=0, vjust=-0.5)
geom_label(data = filter(df_long, name == "cost"), hjust=0, vjust=-0.5)
scale_y_continuous(
name = "Sale and Share",
sec.axis = sec_axis(~., name ="Cost")
)
theme_minimal()
theme(legend.title=element_blank())
ggplotly(plt)
CodePudding user response:
Legend issue:
CodePudding user response:
Further approach from @Quinten's answer,
to handle 'name name' and 'value value' things,
try
tooltip = c("value", "name", "model")
plt1$x$layout$legend$title$text <- "name"
Full code is
plt <-
ggplot(df_long, aes(x = model, y= value, label = NA))
geom_col(data = filter(df_long, name != "cost"), aes(fill=name), position = position_dodge())
scale_fill_manual(values = c("blue", "grey"))
geom_line(data = filter(df_long, name == "cost"), aes( group = 1, color = name), size = 1)
scale_color_manual(values = "red")
#geom_text(data = filter(df_long, name == "cost"), size = 3,hjust=0, vjust=-0.5)
geom_label(data = filter(df_long, name == "cost"), hjust=0, vjust=-0.5)
scale_y_continuous(
name = "Sale and Share",
sec.axis = sec_axis(~., name ="Cost")
)
theme_minimal()
plt1 <- ggplotly(plt, tooltip = c("value", "name", "model"))
for (i in 1:length(plt1$x$data)){
if (!is.null(plt1$x$data[[i]]$name)){
plt1$x$data[[i]]$name = gsub("\\(","",str_split(plt1$x$data[[i]]$name,",")[[1]][1])
}
}
plt1$x$layout$legend$title$text <- "name"