在這里,我有 ggplotly 給出的互動式條形圖。唯一的問題是,當我在條形周圍移動滑鼠時,在“模型”類別中有一個奇怪的數字,而不是 A 或 B(見圖)。是否可以自定義情節彈出視窗?
df <- data.frame (model = c("A", "A","B","B"),
year = c("2022","2021","2022","2021"),
sale = c(350,170,300,150),
change = c(180,NA,150,NA),
percent = c(105.8,NA,100,NA),
info = c("180, 105.8%",NA,"300,100%",NA)
)
#ggplot
plot <- ggplot(df, aes(fill=year, y=model, x=sale))
geom_bar(position="dodge", stat="identity") geom_text(aes(label=info, x=1.11*max(sale),), fontface='bold') xlim(0, 1.2*max(df$sale))
theme(legend.position="bottom") labs(fill = " ")
scale_fill_brewer(palette = "Paired")
ggplotly(plot)
uj5u.com熱心網友回復:
就個人而言,我避免使用它,ggplotly()
因為它經常以我不想要的方式格式化視覺效果。
完整的plotly
方法可能如下所示:
plot_ly(
data = df,
x = ~sale,
y = ~model,
color = ~year,
text = ~year,
type = "bar") %>%
add_trace(
x = ~max(df$sale) * 1.1,
y = ~model,
type = 'scatter',
mode = 'text',
text = ~info,
showlegend = FALSE
) %>%
style(hovertemplate = paste("Sale: %{x}",
"Model: %{y}",
"Year: %{text}",
sep = "<br>"))
您也可以嘗試將style()
物件附加到您的ggplotly()
物件。但是,我不確定這是否可行。
uj5u.com熱心網友回復:
出于某種原因,如果您使用x=model
和翻轉軸,它會更好地作業:
plot <- ggplot(df, aes(fill=year, x=model, y=sale))
geom_bar(position="dodge", stat="identity") geom_text(aes(label=info,y=1.11*max(sale),), fontface='bold')
ylim(0, 1.2*max(df$sale))
theme(legend.position="bottom") labs(fill = " ")
scale_fill_brewer(palette = "Paired")
coord_flip()
ggplotly(plot)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/485232.html
標籤:r ggplot2 情节地 tidyverse 数据可视化
上一篇:如何像這樣繪制兩個重疊的直方圖?