首页 > 解决方案 > 如何在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 中执行此操作的代码是什么

标签: rplot

解决方案


在您的数据中,您在城市下的值似乎是字符。您需要先确保它们是数字。然后你需要将你的数据从宽转换为长,之后你可以简单地geom_pirateggpirate包中使用:

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并将其中的chars更改为 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)

在此处输入图像描述


推荐阅读