在 R/ggplot2 中,當我使用時geom_bar(stat='identity',position='fill'),“銷售”提示顯示“0.80000”,如何將其更改為“80.0%”?(我知道改變一個新的變數使用scales::percent(sales),可以作業geom_point)
library(tidyverse)
library(plotly)
test_data <- data.frame(category=c('A','B','A','B'),
sub_category=c('a1','b1','a2','b2'),
sales=c(1,2,4,5))
p <- test_data %>%
ggplot(aes(x=category,y=sales,
fill=sub_category))
geom_bar(stat='identity',position='fill')
ggplotly(p)

uj5u.com熱心網友回復:
一種選擇(也許是最簡單的一種)是手動計算您的百分比,而不是position = "fill"通過text美學手動使用和創建工具提示,這使得數字樣式變得容易,...隨您喜歡:
library(plotly)
test_data <- data.frame(
category = c("A", "B", "A", "B"),
sub_category = c("a1", "b1", "a2", "b2"),
sales = c(1, 2, 4, 5)
)
test_data <- test_data %>%
group_by(category) %>%
mutate(pct = sales / sum(sales))
p <- test_data %>%
ggplot(aes(x = category, y = pct, fill = sub_category))
geom_col(aes(text = paste0(
"category: ", category, "<br>",
"sub_category: ", sub_category, "<br>",
"sales: ", scales::percent(pct)
)))
ggplotly(p, tooltip = "text")

轉載請註明出處,本文鏈接:https://www.uj5u.com/net/376432.html
下一篇:ggplot折線圖的問題
