Я делаю сюжет сначала в ggplot, а затем делаю его интерактивным с помощью ggplotly.
Но мне нужно, чтобы всплывающая подсказка для текущей цены, называемая «precio_actual» в data.frame, была правильно отформатирована.
Это выглядит как: 1499 во всплывающей подсказке.
Должно быть: 1 4900,00 с/з.
I'm reading the documentation for ggplotly, but cannot find any indication on how to achieve this.
данные:
dput(tail_tvs)
structure(list(ecommerce = c("wong", "wong", "wong", "wong",
"wong", "wong"), marca = c("sony", "samsung", "sony", "samsung",
"daewoo", "samsung"), producto = c("sony smart tv 55'' 4k uhd kd-55x750f android",
"samsung smart tv curvo 65'' 4k uhd 65nu7300", "sony smart tv 40'' full hd kdl-40w655d linux",
"samsung smart tv 55'' 4k uhd 55mu6103", "daewoo smart tv 43'' full hd l43s780bts",
"samsung smart tv 49'' 4k uhd 49mu6400"), precio_antes = c(4499,
4999, 1699, 3599, 1439, 3999), precio_actual = c(2199, 4999,
1299, 3599, 1439, 3999), pulgadas = c(55, 65, 40, 55, 43, 49),
unidades = c(2, 1, 4, 1, 1, 2), descuento = c(-0.51122471660369,
0, -0.235432607416127, 0, 0, 0), rango = c("S/.1500 - S/.2500",
"> S/.4,500", "S/.500 - S/.1500", "S/.3500 - S/.4500", "S/.500 - S/.1500",
"S/.3500 - S/.4500")), class = c("tbl_df", "tbl", "data.frame"
), row.names = c(NA, -6L))
код:
tt10 <- "Precio de televisores según su tamaño (pulgadas)"
stt10 <- "\n"
pulgadas_precio <- ggplot(tail_tvs, aes(x = pulgadas, y = precio_actual)) +
geom_point(aes(color=marca),size = 4,alpha = 0.6) +
facet_grid(~ ecommerce) +
theme_ipsum_rc(grid = "Y") +
theme(axis.text.x = element_text(colour = "grey10",size=10,hjust=.5,vjust=.5,face = "plain"),
axis.text.y = element_text(colour = "grey10",size=10,hjust=1,vjust=0,face = "plain"),
axis.title.x = element_text(colour = "grey40",size=16,angle=0,hjust=.5,vjust=0,face = "plain"),
axis.title.y = element_text(colour = "grey40",size=16,angle=90,hjust=.5,vjust=.5,face = "plain"),
plot.title = element_text(size = 24,vjust=4, face = "bold"),
plot.subtitle = element_text(vjust=2, size = 16),
plot.caption = element_text(vjust=2, size = 16),
legend.title = element_text(colour = "grey40",size=14,hjust=.5,vjust=.5,face = "bold"),
legend.text = element_text(colour = "grey10", size=18, face = "plain"),
strip.text.x = element_text(size = 18, angle = 0),
strip.text.y = element_text(size=14, face = "bold"),
legend.position = "none") +
scale_y_continuous(label=comma, limits = c(0,50000)) +
scale_x_continuous(label=comma, limits = c(0,100)) +
labs(title = tt10, subtitle = stt10, caption = cptn,
x = "pulgadas \n", y = "precio en S/. \n") +
scale_color_discrete(name = "marcas de tvs") +
geom_smooth()
ggplotly(pulgadas_precio, tooltip=c("marca", "pulgadas", "precio_actual"))





Я обнаружил, что вы можете использовать аргумент text в aes и сделать следующее:
ggplot(tail_tvs, aes(x = pulgadas, y = precio_actual, text = sprintf("S/ %s", comma(precio_actual))))
Обратите внимание, что я форматирую часть S/ и comma separetor для тысяч в этом текстовом аргументе.
Теперь при вызове ggplotly вместо
ggplotly(pulgadas_precio, tooltip=c("marca", "pulgadas", "precio_actual"))
Вы вызываете текстовый аргумент вместо исходной переменной:
ggplotly(pulgadas_precio, tooltip=c("marca", "pulgadas", "text"))
К сожалению, ваш код не запускается, поэтому я не могу написать для вас решение и протестировать его, НО...
Вы захотите передать отформатированную строку, представленную в этот пост StackOverflow.
Для специального форматирования валюты я рекомендую написать собственную функцию, например. mycurrency(x), который возвращает отформатированную строку значения, которое вы ему передаете. Используйте его, как предложено ниже.
# draw the line plot using ggplot
gg <-ggplot(plotbycity, aes(x = date, y = rent, group = city, color = city,
text = paste('Rent:', mycurrency(rent),
'<br>Date: ', as.Date(date),
'<br>Obs: ', count))) +
geom_line() +
ggtitle("Monthly Rents")
p <- ggplotly(gg, tooltip = c("text"))
Ниже приведен пример простого метода форматирования валюты (вдохновленный эта почта)
mycurrency <- function(x){
return(paste("$", formatC(as.numeric(x), format = "f", digits=2, big.mark = ",")))
}