I want the black numbers (x-axis labels) to be attached closely below each corresponding bar. red numbers show the results I desire.
the labels I will use are long names that are longer than these numbers but I replaced them with numbers for simplicity's sake.
the change values (changes) I want to plot are
-2.9900 -2.7300 -2.3100 -1.8000 -1.6800 -1.2700 -1.0500 -1.0400 -0.9200 -0.6600 -0.6400 -0.5900 -0.5000 -0.4900 -0.4200 -0.3800 -0.0500 -0.0300 -0.0200 -0.0100 -0.0100 -0.0100 -0.0100 -0.0100 -0.0100 -0.0100 -0.0100 -0.0040 -0.0040 -0.0005 0.0030 0.4300 0.4500 0.5500 0.6100 0.6200 0.6200 0.6400 2.7200 5.6900
numbers<- 1:40
#barplot
rt<-barplot(change, main = "change in metabolites after Ramadan ",
col = c('grey','grey','grey','grey','grey','grey','grey','grey','grey','grey','grey','grey','grey','grey','grey','grey','grey','grey','grey','grey','grey','grey','grey','grey','grey','grey','grey','grey','grey','grey','grey','grey','grey','grey','grey','grey','grey','grey','grey','grey'),
names = numbers,
ylab = "percentage of Change (%)",
ylim = c(-4, 6))
Thank you in advance
Best,
CodePudding user response:
One option is to add an offset to each label position depending on whether it is below or above zero, e.g.
change <- c(-2.9900, -2.7300, -2.3100, -1.8000, -1.6800,
-1.2700, -1.0500, -1.0400, -0.9200, -0.6600,
-0.6400, -0.5900, -0.5000, -0.4900, -0.4200,
-0.3800, -0.0500, -0.0300, -0.0200, -0.0100,
-0.0100, -0.0100, -0.0100, -0.0100, -0.0100,
-0.0100, -0.0100, -0.0040, -0.0040, -0.0005,
0.0030, 0.4300, 0.4500, 0.5500, 0.6100,
0.6200, 0.6200, 0.6400, 2.7200, 5.6900)
numbers<- 1:40
rt<-barplot(change, main = "change in metabolites after Ramadan ",
col = c('grey','grey','grey','grey','grey','grey','grey','grey','grey','grey','grey','grey','grey','grey','grey','grey','grey','grey','grey','grey','grey','grey','grey','grey','grey','grey','grey','grey','grey','grey','grey','grey','grey','grey','grey','grey','grey','grey','grey','grey'),
names = numbers,
ylab = "percentage of Change (%)",
ylim = c(-4, 6.5))
text(x = rt, y = ifelse(change <= 0, change - 0.25, change 0.25),
labels = numbers, cex = 0.6, srt = -90, col = "red")