r - 如何使用 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
错误
解决方案
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)
推荐阅读
- reactjs - 哪个可排序的 npm 包最适合 react 17 中的图像列表?
- r - 是否有重新排列数据框以在 R 中绘图的功能?
- javascript - 为什么我的 document.getElementsByClassName("obj").innerHTML 不起作用?
- javascript - 为什么我的 JavaScript 文件在没有任何明显错误的情况下崩溃?
- python - python 多处理同时列出文件并从列表中提取数据?
- html - 定制使用 CSS
- python - 如何将时间列转换为 Unix 时间戳?
- android - Android apk 签名会被篡改吗?
- flutter - 如何在文本小部件中添加文本字段?- 颤振
- javascript - ./src/Firebase.js 模块未找到:无法解析“C:\Users\HP\Desktop\React\clone\disney-plus-clone\src”中的“firebase”