gpt4 book ai didi

r - 修改ggplot2中圆环图百分比标签的位置和格式

转载 作者:行者123 更新时间:2023-12-04 16:12:24 28 4
gpt4 key购买 nike

我用下面的代码绘制了一个 donut chart :

library(tidyverse)
library(ggthemes)

df <- data.frame(flavor = c("Chocolate", "Strawberry", "Pistachio"),
per_sold = c(.20, .30, .50))
df %>%
ggplot(aes(x = 2, y = per_sold, fill = flavor)) +
geom_bar(stat = "identity") +
xlim(0.5, 2.5) +
coord_polar(start = 0, theta = "y") +
xlab("") +
ylab("") +
theme(axis.ticks = element_blank(),
axis.text = element_blank(),
axis.title = element_blank(),
panel.grid = element_blank(),
panel.border = element_blank(),
legend.title = element_text(size = rel(2)),
legend.text=element_text(size=rel(1.5))) +
geom_text(aes(label = per_sold), size = 6)
出去:
enter image description here
如您所见,标签的位置不正确,我希望它显示 % 的格式而不是带数字的浮点数。
我怎样才能修改代码来实现这一点?谢谢。

最佳答案

您只需要position_stack(vjust = 0.5)scales::percent :

library(scales)
df %>%
ggplot(aes(x = 2, y = per_sold, fill = flavor)) +
geom_bar(stat = "identity") +
xlim(0.5, 2.5) +
coord_polar(start = 0, theta = "y") +
xlab("") +
ylab("") +
theme(axis.ticks = element_blank(),
axis.text = element_blank(),
axis.title = element_blank(),
panel.grid = element_blank(),
panel.border = element_blank(),
legend.title = element_text(size = rel(2)),
legend.text=element_text(size=rel(1.5))) +
geom_text(aes(label = scales::percent(per_sold)),
size = 6, position = position_stack(vjust = 0.5))
enter image description here

关于r - 修改ggplot2中圆环图百分比标签的位置和格式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62807306/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com