首页 > 解决方案 > 我如何使用数据框中的值在 ggplot 2 中绘制图形并将它们转换为四舍五入的百分比标签

问题描述

我有这些价值观

PCT_Asian | PCT_Black | PCT_Hispanic | PCT_White | PCT_Other
.26554     .25454     .145454         .22454      .23123

我想看到一个条形图,其中每个 bin 下的 x 轴标签

PCT_Asian to Asian
PCT_Black to Black
Pct_White to White and so on.....

还将值转换为适当的百分比标签

27%、25%、15%、22% 和 23%

标签: rggplot2label

解决方案


你可以试试

library(tidyverse)
a <- str_split("PCT_Asian | PCT_Black | PCT_Hispanic | PCT_White | PCT_Other", "[|]", simplify = T) %>% str_trim(.)
b <- str_split(".26554     .25454     .145454         .22454      .23123", " ", simplify = T) %>% as.numeric(.) %>% na.omit(.)
tibble(a, b) %>% 
  mutate(x = str_remove(a, "PCT_")) %>% 
  ggplot(aes(x, b)) + 
   geom_col() + 
   scale_y_continuous(labels = scales::percent)

在此处输入图像描述


推荐阅读