Name Value1 Value2 Value3
1 A1 -0.05970872 -1.1651404 1.3516952
2 A2 0.44143488 -0.7270722 -1.9870423
3 A3 0.34616897 -0.3891095 0.9123736
4 A4 0.49289331 1.3957877 -0.2689896
5 A5 -1.39354557 0.9429327 1.0719274
I have the above dataframe, and I want to generate four graphs for it in ggplot2, each having the x axis as the "Name" column and the y axis as the other columns' values. While the x-axis won't need to have "tick marks", I do want to conditionally label the points with the name of their corresponding "Name" column value if the y-axis is below a cutoff, say 0. Below is my code using the basic plot function in R to generate the graphs automatically with loop function. I've attached one sample graph.
cutoff = 0
df = read.csv("Book4.csv", header = TRUE)
list = rownames(df)
for(i in names(df)){
png(filename = paste(i,".png"))
plot(df[,i],
main = i,
ylab = "Values",
xlab = "Names",
col = ifelse(df[,i]<cutoff, 'red', 'gray'),
pch = ifelse(df[,i] < cutoff, 10, 1)
)
abline(cutoff, 0, col= "blue", lty=2)
outlier = which(df[,i]<=cutoff)
if (length(outlier)>0){
text(outlier, df[outlier,i], list[outlier], cex=0.7, pos=2)
}
dev.off()
}

The issue is that these graph labels often are hidden, or when I use larger datasets overlap so I can't read them. Hence, I wanted to reproduce this using ggplot2 and the function geom_text_repel. I have attempted using for loops to do this, but got stuck at the implementation of the point labelling with geom_text_repel, as I wasn't sure how to conditionally label with that. I will be producing upwards of 200 pngs, so I'd greatly appreciate if it could be automated and outputted with the filename as "Value1.png", "Value2.png" and so forth.
Here is my attempt in ggplot below
cutoff = 0
df = read.csv("Book4.csv", header = TRUE, row.names = 1)
for(i in colnames(df)){
png(filename = paste(i,".png"))
outlier = which(df[,i]<=cutoff)
print(ggplot(df, aes(x = rownames(df), y = df[,i])) +
geom_point() +
geom_text_repel(data = df, label=outlier))
dev.off()
}
I keep getting the error "Error: Aesthetics must be either length 1 or the same as the data (5): label" and am not sure hwo to fix that.



