I created a histogram with a number (count) of subjects on the y-axis and I'm trying to find a way to add the ID label of each ID on each bar of the histogram. I tried geom_text and geom_text_repel but I still can't get the number to be organized exactly on each bar for each subject.
For my dataset I'm reading a CSV file with 72 subjects, the columns are ID and Drugratio
ggplot code:
plot_5 <- ggplot(All_data, aes(x=as.numeric(logMRP), fill = as.factor(PATIENTID))) geom_histogram(aes( bins = 30, label=as.factor(PATIENTID))) geom_text( stat='count', aes(label=ID), color="Black", size=3, check_overlap = TRUE, hjust=1, position=position_stack(vjust=0.5 )) theme(legend.position = "none")
show(plot_5)
Any suggestions! Thank you
CodePudding user response:
Without your data or code, we can only guess, but it seems your data is something like this:
set.seed(4)
df <- data.frame(ID = factor(1:72), value = 2 - rgamma(72, 3, 2))
And your plotting code is like this:
library(ggplot2)
ggplot(df, aes(value, fill = ID))
geom_histogram(bins = 30)
geom_text(stat = "count", aes(label = ID, y = ..count..),
check_overlap = TRUE)
guides(fill = guide_none())
labs(x = NULL)
This looks very similar to your own plot. To fix it, let's use stat_bin
with position = position_stack()
for the text layer.
ggplot(df, aes(x = value, fill = ID))
geom_histogram(bins = 30)
stat_bin(geom = "text", bins = 30, na.rm = TRUE,
aes(label = ifelse(after_stat(count) == 0, NA, after_stat(group)),
group = ID, y = after_stat(count)),
position = position_stack(vjust = 0.5))
guides(fill = guide_none())
labs(x = NULL)
Created on 2022-09-01 with reprex v2.0.2
CodePudding user response:
Following the great suggestions I got from Allan Cameron, I was able to add the ID values for each subject as shown the graph and using the code below
The only issue now is that the numbers are not matching the exact IDs in each column
I would greatly appreciate your suggestions!
plot_5_new <- ggplot(All_data, aes(x=as.numeric(logMRP), fill = as.factor(ID))) geom_histogram(bins=30) stat_bin(geom = "text", bins = 30, na.rm = TRUE, aes(label = ifelse(after_stat(count) == 0, NA, after_stat(group)), group = as.factor(ID), y = after_stat(count)),position = position_stack(vjust = 0.5)) guides(fill = guide_none()) theme(legend.position = "none") show(plot_5_new)