r - 如何在R中制作海盗情节
问题描述
我有看起来像这样的数据:
Age New_York Boston Chicago
1 under 1 994 969 1011
2 1 991 1094 1282
3 2 991 1369 1274
4 3 818 1051 1098
5 4 902 1012 1308
6 5 866 1077 1040
7 6 826 1684 929
8 7 793 1071 1077
9 8 714 1387 984
10 9 890 855 749
这是生成我的数据的代码:
structure(list(Age = c("under 1", "1", "2", "3", "4", "5", "6",
"7", "8", "9"), New_York = c("994", "991", "991", "818", "902",
"866", "826", "793", "714", "890"), Boston = c("969", "1094",
"1369", "1051", "1012", "1077", "1684", "1071", "1387", "855"
), Chicago = c("1011", "1282", "1274", "1098", "1308", "1040",
"929", "1077", "984", "749")), .Names = c("Age", "New_York",
"Boston", "Chicago"), row.names = c(NA, 10L), class = "data.frame")
我正在尝试在 R 中制作一个海盗情节,其中将 Age 作为 IV 以及不同城市的答案。我想知道在 R 中执行此操作的代码是什么
解决方案
在您的数据中,您在城市下的值似乎是字符。您需要先确保它们是数字。然后你需要将你的数据从宽转换为长,之后你可以简单地geom_pirate
从ggpirate
包中使用:
install.packages('devtools')
devtools::install_github("mikabr/ggpirate")
library(ggpirate)
df_long <- gather(df_wide[,c(2:4)], key = "City", value = "Value")
ggplot(df_long, aes(City, Value)) +
geom_pirate(aes(col = City), show.legend = TRUE)
请注意,我命名了您的原始数据集df_wide
并将其中的char
s更改为 s num
。
编辑:或者,您可以使用包中的pirateplot()
功能yarrr
:
library(yarrr)
df <- structure(list(Age = c("under 1", "1", "2", "3", "4", "5", "6",
"7", "8", "9"), New_York = c("994", "991", "991", "818", "902",
"866", "826", "793", "714", "890"), Boston = c("969", "1094",
"1369", "1051", "1012", "1077", "1684", "1071", "1387", "855"
), Chicago = c("1011", "1282", "1274", "1098", "1308", "1040",
"929", "1077", "984", "749")), .Names = c("Age", "New_York",
"Boston", "Chicago"), row.names = c(NA, 10L), class = "data.frame")
df$New_York <- as.numeric(df$New_York)
df$Boston <- as.numeric(df$Boston)
df$Chicago <- as.numeric(df$Chicago)
df_long <- gather(df[,c(2:4)], key = "City", value = "Value")
pirateplot(formula = Value ~ City,
data = df_long)
推荐阅读
- javascript - 如何柏树等待元素的转换
- database - 如何在 Material UI 表中实现 Dynamodb 分页
- pca - 如何在具有向量元素的矩阵上进行 PCA?
- java - 添加地图框依赖时出现毕加索依赖错误
- python - Python:从减法/加法构造一个类
- python - python中的Unix时间转换
- .htaccess - 防止浏览器缓存 .htaccess 文件本身
- reactjs - 使用反应确定日期是星期六还是星期日
- dialog - 如何在 dm-script 中创建具有两个以上按钮的阻止对话框
- python - pd.read_excel 仅文件名在过去 5 天内包含子字符串的文件