【问题标题】:barplot grouped by 2 columns按 2 列分组的条形图
【发布时间】:2018-10-21 21:44:28
【问题描述】:

我有一个从文件中读出的 tibble(见下文)。我想通过以下方式从小标题中绘制条形图:

x 轴应按player_name 分组,skill_type 应具有相同的颜色。条的高度应等于breakpoint_rate。底部应该是每个条的数字n_serves

我尝试转换为矩阵或数据框,但没有任何效果。由于我是 R 新手,因此我决定在这里询问很多细节。

这是dput 给出的小标题的代码:

structure(list(player_name = c("John HYDEN", "John HYDEN", "Nikita 
LIAMIN", "Theodore BRUNNER", "Viacheslav KRASILNIKOV", "Viacheslav 
KRASILNIKOV"), skill_type = c("Jumpfloat", "Standing serve", "Jumpfloat", 
"Jumpfloat", "Jump serve", "Jumpfloat"), n_serves = c(15L, 3L, 24L, 14L, 
16L, 1L), breakpoint_rate = c(0.4, 0, 0.583333333333333, 
0.285714285714286, 0.375, 0)), class = c("grouped_df", "tbl_df", "tbl", 
"data.frame"), row.names = c(NA, -6L), vars = "player_name", drop = TRUE)

我尝试过的代码:

## Attempt with conversion to matrix
PWS_mat <- t(as.matrix(PWS_K2_infos))
barplot(`colnames<-`(t(PWS_mat[-c(1,2)]), PWS_mat[,2]), beside=TRUE, 
    legend.text = TRUE, col = c("red", "green"), 
    args.legend = list(x = "topleft", bty = "n", inset=c(-0.05, 0)), xlab="Serviceart", ylab="Breakpointchance")

导致错误...

## Attempt with conversion to dataframe
PWS_df <- as.data.frame(select(PWS_K2_infos,-n_serves))
barplot(`colnames<-`(t(PWS_df[-c(1,2)]), PWS_df[,2]), beside=TRUE,  
    legend.text = TRUE, col = c("red", "green"), 
    args.legend = list(x = "topleft", bty = "n", inset=c(-0.05, 0)), xlab="Serviceart", ylab="Breakpointchance")

这个给了我一个条形图,但我没有按照我想要的方式对其进行分组。

【问题讨论】:

  • 欢迎来到 Stack Overflow!请不要将您的数据作为图像提供。没有人想再次全部输入。相反,请使用 dput 制作您数据的文本版本,我们可以将您的问题中的数据剪切并粘贴到 R 中。
  • 请贴出您尝试过的代码。

标签: r bar-chart tibble


【解决方案1】:

我现在找到了一个不同的解决方案,使用 ggplot。这几乎对我有用,只有格式有点偏离,以防一组的条数与另一组不同。那么geom_text产生的标签不在条的中心。其余的工作正常。

如果其他人需要这个,这里是我现在使用的代码:

ggplot(PWS_K2_infos, aes(player_name, breakpoint_rate, fill = skill_type)) + 
geom_bar(stat="identity", position = position_dodge(preserve = "single"), width=0.9)+ 
geom_text(aes(label = round(breakpoint_rate, digits=2)), vjust=-0.3, position = position_dodge(0.9), size=3.5) +
geom_text(aes(label = paste("n=",n_serves)), vjust=1.6, color="white", position = position_dodge(0.9), size=3.5)+
ggtitle("Breakpoint% nach Serviceart") + 
xlab("") + ylab("Breakpunkt %") + 
scale_fill_brewer(palette = "Dark2")

【讨论】:

    猜你喜欢
    • 2018-08-22
    • 2021-03-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多