首页 > 解决方案 > 按年份划分的小提琴情节

问题描述

我今天在 ggplot 中对 geom_violin 没有任何运气。有什么帮助吗?

我在当地比赛中有 10 年的跑步时间。我想绘制每年前 10 次的分布。例如:2018 年:14:51-17:29、2017 年:15:03-18:22 等

每次我运行代码时,它都会为我提供 10 年内前 10 名的分布(100 个数据点),而不是每年细分(每年 10 个数据点)。

代码:

violin <- 5kAthletes %>%
  filter(Category=="Top10")

(^^^这对我来说很合适^^^

vplot<-violin %>%
  ggplot(aes(x=Year, y=Minutes, fill=Year)) +
  geom_violin() +
  xlab("Year") +
  theme(legend.position = "none") +
  xlab("")  
vplot

标签: rggplot2violin-plot

解决方案


你必须增加group = Year美学,即ggplot(aes(x=Year, y=Minutes, fill=Year, group = Year))。使用gapminder数据集作为示例数据:

library(ggplot2)
library(dplyr)
library(gapminder)

df <- gapminder::gapminder %>% 
  group_by(year) %>% 
  top_n(10, lifeExp)

vplot <- df %>%
  ggplot(aes(x=year, y=lifeExp, fill=year, group = year)) +
  geom_violin() +
  xlab("Year") +
  theme(legend.position = "none") +
  xlab("")  
vplot

reprex 包(v0.3.0)于 2020 年 4 月 2 日创建


推荐阅读