首页 > 解决方案 > 如何使用 ggplot barplot 绘制表函数的结果(x 轴值问题)

问题描述

我有一个数据框,我使用表函数来查找变量“环绕”和“发行”的比率。这是我写的代码:

out <- table( df_select$Insured_Age_Group,df_select$Policy_Status)
out <- cbind(out, ratio = out[,2]/rowSums(out))

此代码的结果如下所示:

  Issuance Surrended     ratio
1    31046      5735 0.1559229
2    20039      4409 0.1803420
3    20399      9228 0.3114726
4    48677     17216 0.2612721
5    30045      8132 0.2130078
6    13947      4106 0.2274414
7     3157      1047 0.2490485

如果您需要代码来生成此数据框:

structure(c(31046, 20039, 20399, 48677, 30045, 13947, 3157, 5735, 
4409, 9228, 17216, 8132, 4106, 1047, 0.155922894972948, 0.18034195026178, 
0.311472643197084, 0.261272062282792, 0.213007831940697, 0.227441422478258, 
0.249048525214082), .Dim = c(7L, 3L), .Dimnames = list(c("1", 
"2", "3", "4", "5", "6", "7"), c("Issuance", "Surrended", "ratio"
)))

现在我想为每个组绘制这些比率。我想知道我应该如何将 x 数字传递给 ggplot?基本上,这里我的 x 是 (1,2,3,4,5,6,7),它们是 7 个年龄组。我应该手动将它传递给ggplot吗?像我在下面展示的那个?或者有更好的方法吗?

ggplot(data=out, aes(x=c(1,2,3,4,5,6,7), y=ratio)) +
  geom_bar(stat="identity", position=position_dodge()) +
  theme(legend.position = "right")+
  xlab("")+
  geom_text(aes(label=Total), vjust=-0.5 , hjust=0.7, color="black", position = position_dodge(0.9),size=3)

但这会返回Error: 数据 must be a data frame, or other object coercible by fortify(), not a numeric vector错误

标签: rggplot2bar-chart

解决方案


out是一个矩阵,将其转换为数据框。最好创建要在数据本身中绘制的新列。不知道是什么Total,但我正在使用ratio列的标签。

library(dplyr)
library(ggplot2)

data.frame(out) %>%
  mutate(x = row_number()) %>%
  ggplot(aes(x, ratio)) +
  geom_bar(stat="identity", position=position_dodge()) +
  theme(legend.position = "right")+
  xlab("")+
  geom_text(aes(label=round(ratio, 2)), vjust=-0.5 , hjust=0.7, color="black", position = position_dodge(0.9),size=3)

在此处输入图像描述


推荐阅读