Create violin plot with specific value label that corresponding to graph
1
0
Entering edit mode
3.2 years ago

Hello, I need some helps to plot the graph in R. I want to label specific values on my density plot graph by using ggplot package. How to write geom_text or geom_label to label them just like this graph that labels 10,30,40,60,100 and 150 on each plot. And How to add the mean line to the violin plot? Thanks in advance enter image description here

R • 1.4k views
ADD COMMENT
3
Entering edit mode
3.2 years ago

Example data.

# Counts
df <- as.data.frame(sapply(seq(2, 10, 2), function(x) rnorm(10, x, 1)))
colnames(df) <- paste0("group_", 1:5)
df$val <- paste0("val_", 1:10)

> df
     group_1  group_2  group_3  group_4   group_5    val
1  0.4267759 4.599173 6.256323 8.534080 12.778423  val_1
2  2.9344611 3.649858 7.141283 9.299478 10.735906  val_2
3  0.8156248 3.363994 7.285855 7.503840  9.755979  val_3
4  3.6260469 5.262640 5.610248 9.644565 11.123747  val_4
5  2.7633611 5.229914 6.530228 7.705648  9.742567  val_5
6  0.4645319 4.294645 4.535441 7.936977 11.188125  val_6
7  1.7285739 3.044876 5.599020 7.355119 10.132674  val_7
8  0.9213467 3.447743 7.075501 6.410716  9.288704  val_8
9  2.7842446 3.318985 6.190816 8.367641 10.786482  val_9
10 1.7583467 3.329080 7.518858 7.125112 11.276875 val_10

# Label key
lab <- data.frame(group=paste0("group_", 1:5), lab=seq(1, 9, 2))

> lab
    group lab
1 group_1   1
2 group_2   3
3 group_3   5
4 group_4   7
5 group_5   9

Pivot the data to long format and plot.

library("tidyverse")

df %>%
  pivot_longer(!val, names_to="group", values_to="count") %>%
  ggplot(aes(x=group, y=count)) + geom_violin() +
    geom_errorbar(data=lab, aes(x=group, y=lab, ymin=lab, ymax=lab)) +
    geom_text(data=lab, aes(x=group, y=lab, label=lab), nudge_x=-0.5) +
    stat_summary(geom="errorbar", fun=mean, fun.max=mean, fun.min=mean, lty=2)

enter image description here

ADD COMMENT
0
Entering edit mode

Thanks, that help a lot!

ADD REPLY

Login before adding your answer.

Traffic: 2623 users visited in the last hour
Help About
FAQ
Access RSS
API
Stats

Use of this site constitutes acceptance of our User Agreement and Privacy Policy.

Powered by the version 2.3.6