在 ggplot 条形图上添加最多两位小数的百分比
Adding percentages up to two decimals on to of ggplot bar chart
我想知道是否有人知道如何在 ggplot 条形图中将 magnitudes/measurements 的标签作为最多两位小数的百分比。
现在这是我得到的:
df <- data.frame(Seller=c("Ad","Rt","Ra","Mo","Ao","Do"),
Avg_Cost=c(5.30,3.72,2.91,2.64,1.17,1.10), Num=c(6:1))
str(df)
plotB <- ggplot(df, aes(x = reorder(Seller, Avg_Cost), y = Avg_Cost)) +
geom_col( width = 0.7) +
coord_flip() +
geom_bar(stat="identity", fill="steelblue") +
theme( panel.background = element_blank(), axis.title.x = element_blank(),
axis.title.y = element_blank()) +
geom_text(aes(label=Avg_Cost), size=5, hjust=-.2 ) +
ylim(0,6)
plotB
我想要的输出应该显示 5.30%、3.72%、2.91% ....
我尝试使用:geom_text(aes(label=scales::percent( ), y= ), size=6, hjust=-.2 )
问题是无论我如何舍入,它都会给我小数点后三位。
提前致谢。
只需使用sprintf
:
sprintf("%0.2f%%", df$Avg_Cost)
# [1] "5.30%" "3.72%" "2.91%" "2.64%" "1.17%" "1.10%"
plotB <- ggplot(df, aes(x = reorder(Seller, Avg_Cost), y = Avg_Cost)) +
geom_col( width = 0.7) +
coord_flip() +
geom_bar(stat="identity", fill="steelblue") +
theme( panel.background = element_blank(), axis.title.x = element_blank(),
axis.title.y = element_blank()) +
geom_text(aes(label = sprintf("%0.2f%%", Avg_Cost)), size=5, hjust=-.2 ) +
### ^^^^ this is your change ^^^^
ylim(0,6)
我想知道是否有人知道如何在 ggplot 条形图中将 magnitudes/measurements 的标签作为最多两位小数的百分比。
现在这是我得到的:
df <- data.frame(Seller=c("Ad","Rt","Ra","Mo","Ao","Do"),
Avg_Cost=c(5.30,3.72,2.91,2.64,1.17,1.10), Num=c(6:1))
str(df)
plotB <- ggplot(df, aes(x = reorder(Seller, Avg_Cost), y = Avg_Cost)) +
geom_col( width = 0.7) +
coord_flip() +
geom_bar(stat="identity", fill="steelblue") +
theme( panel.background = element_blank(), axis.title.x = element_blank(),
axis.title.y = element_blank()) +
geom_text(aes(label=Avg_Cost), size=5, hjust=-.2 ) +
ylim(0,6)
plotB
我想要的输出应该显示 5.30%、3.72%、2.91% ....
我尝试使用:geom_text(aes(label=scales::percent( ), y= ), size=6, hjust=-.2 )
问题是无论我如何舍入,它都会给我小数点后三位。 提前致谢。
只需使用sprintf
:
sprintf("%0.2f%%", df$Avg_Cost)
# [1] "5.30%" "3.72%" "2.91%" "2.64%" "1.17%" "1.10%"
plotB <- ggplot(df, aes(x = reorder(Seller, Avg_Cost), y = Avg_Cost)) +
geom_col( width = 0.7) +
coord_flip() +
geom_bar(stat="identity", fill="steelblue") +
theme( panel.background = element_blank(), axis.title.x = element_blank(),
axis.title.y = element_blank()) +
geom_text(aes(label = sprintf("%0.2f%%", Avg_Cost)), size=5, hjust=-.2 ) +
### ^^^^ this is your change ^^^^
ylim(0,6)