我从文件中读出了一个小标题(请参阅下文)。我想通过以下方式来绘制小标题:
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")
这个给了我一个barplot,但是我没有按照我想要的方式对它进行分组。
答案 0 :(得分:0)
我现在使用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")