I want to plot a violin ggplot where the x-axis are the years and the y-axis is the value. In each year, I need to have three of the violin plots. When I try to do so, the y-axis are not stacked together, so the density of these three isn't shown clearly. In each year, I want them to be plotted in the same y-axis and the fill color be transparent so all three can be seen. The dataset is pretty long (it was pretty hard to replicate a shorter one) but it is three dataframes of sum1.14
, sum5.14
and sum10.14
.
plot.density.tenor <- function(cent_list_sum1,cent_list_sum5,cent_list_sum10,start_year,end_year){
df1 <- melt(ldply(cent_list_sum1, data.frame))
df5 <- melt(ldply(cent_list_sum5, data.frame))
df10 <- melt(ldply(cent_list_sum10, data.frame))
df <- rbind(df1,df5,df10)
years <- seq(start_year,end_year)
df$year <- rep(rep(as.character(seq(start_year,end_year)),each=nrow(df1)/length(years)),3)
df$tenor <- rep(c("1","5","10"),each=nrow(df1))
df$tenor <- factor(df$tenor, levels=c("1", "5", "10"))
ggplot(df, aes(year, value, color = tenor))
geom_flat_violin()
ggtitle("Centrality Measure Distribution") ylab("Centrality") xlab("Year")
stat_summary(colour="red", size = 0.5)
#theme(legend.position = "none")
}
plot.density.tenor(sum1.14,sum5.14,sum10.14,2010,2021)
CodePudding user response:
I can replicate something similar with this fake data:
set.seed(42)
fake <- data.frame(year = as.character(rep(2010:2021, each = 30)),
tenor = rep(c("1", "5", "10"), times = 120),
value = rnorm(360, mean = 0.5))
library(PupillometryR)
library(ggplot2)
ggplot(fake, aes(year, value, color = tenor))
geom_flat_violin()
stat_summary(colour="red", size = 0.5)
I think we can get something like what you're describing with the code below. First we override the defaults to make each plot wider (this will probably need adjustment for different data), then tell the "dodging" function that there should be zero space inserted between the baseline of each successive "tenor" group.
ggplot(fake, aes(year, value, fill = tenor))
geom_flat_violin(width = 15,
position = position_dodge(width = 0),
alpha = 0.5)
stat_summary(colour="red", size = 0.5)