我想在每個部分中正確寫出百分比?如何在每個部分中寫好百分比?如果 plot_ly 更容易,我就可以了。
代碼 :
mois = c("avril", "avril", "avril", "avril", "mai", "mai", "mai", "mai", "juin", "juin", "juin", "juin", "juillet", "juillet", "juillet", "juillet", "aout", "aout", "aout", "aout", "sept", "sept", "sept", "sept")
pourcentage = c(56.7, 10.0, 13.3, 20.0, 64.5, 0.0, 3.2, 32.3, 73.3, 6.7, 3.3, 16.7, 54.8, 12.9, 9.7, 22.6, 45.2, 12.9, 6.5, 35.5, 10.0 , 0.0, 3.3, 86.7)
class = c("=< -5%", "-5 et 0 %", "0 - 5%", ">= 5%", "=< -5%", "-5 et 0 %", "0 - 5%", ">= 5%", "=< -5%", "-5 et 0 %", "0 - 5%", ">= 5%", "=< -5%", "-5 et 0 %", "0 - 5%", ">= 5%", "=< -5%", "-5 et 0 %", "0 - 5%", ">= 5%", "=< -5%", "-5 et 0 %", "0 - 5%", ">= 5%" )
table = as.data.frame(cbind(mois, pourcentage, class))

color <- c("green", "blue", "red", "yellow")
bar = table %>%
ggplot(mapping = aes(x = mois,
y = pourcentage))
geom_bar(aes(fill = class),
position = 'fill', # Use position = fill to use proportions.
stat = 'identity',
color = "black")
scale_y_continuous(labels = scales::percent)
geom_text(aes(label = paste0(pourcentage,"%")),
position = position_fill(vjust = 0.5,
reverse = TRUE),
size = 2)
theme_classic()
scale_fill_manual(values = color)
ggplotly(bar)

uj5u.com熱心網友回復:
兩件事情:
- 您的文本定位有
reverse = TRUE引數。你需要在酒吧上相同的讓他們對齊。 - 您的條形已填充映射到
class,這告訴 ggplot 根據該變數及其排序方式進行條形堆疊。文本沒有指定填充或顏色,因此堆疊將按照資料中的出現順序進行。為了使它以相同的方式堆疊,您可以指定group = class全域(正如我所做的那樣)或aes()為geom_text圖層指定。
修改:
table %>%
ggplot(mapping = aes(x = mois,
y = pourcentage, group = class))
geom_bar(aes(fill = class),
position = position_fill(reverse = TRUE), # Use position = fill to use proportions.
stat = 'identity',
color = "black")
scale_y_continuous(labels = scales::percent)
geom_text(aes(label = paste0(pourcentage,"%")),
position = position_fill(vjust = 0.5,
reverse = TRUE),
size = 2)
theme_classic()
scale_fill_manual(values = color)

轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/335795.html
