BAMF4bacon
BAMF4bacon

Reputation: 603

ggplot in R: barchart with log scale label misplacement

So I have a bar chart to make, and a log plot for y axis is warranted because of the data range. So the problem is I have the value of 0.5, which in log10 is -0.3. Since the bar goes into negative, the "top" of the bar, which is used for placing the labels is actually the "bottom" and so my text label is "just above" the bottom, which means in the middle of the bar. I figure I am probably not the first person with this issue, but searching for related fixes has not helped. Most notably, I tried using dodge, but this does not change that the "top" of the bar is really the "bottom".

So two questions:

  1. Can I fix this label mishap?
  2. This is just ugly: can I move the x axis up to y=1 to give more context to the negative value without moving the x axis labels?

.

alpha=c('A','B','C','D')
value=c(0.5,10,40,1100)
table<-as.data.frame(alpha)
table<-cbind(table, value)
library(ggplot2) 
graph <- ggplot(table, aes(x=alpha)) + 
  geom_bar(stat="identity",aes(y=value),width=0.5) + 
  geom_text(aes(y=value,label=value),vjust=-0.5) + 
  scale_y_continuous(trans="log10",limits=c(0.5,1400))
graph + theme_classic()

graph with labels incorrect

Upvotes: 3

Views: 780

Answers (1)

Barranka
Barranka

Reputation: 21067

A little trick modifying the y coordinate of the data labels (use ifelse() to set the value of y to 1 if the value is less than one). As for the axis, simply hide the X axis (setting it to element_blank()) and draw a new horizontal line:

graph <- ggplot(table, aes(x=alpha)) + 
  geom_bar(stat="identity",aes(y=value),width=0.5) + 
  # Modify the placing of the label using 'ifelse()':
  geom_text(aes(y=ifelse(value < 1, 1, value),label=value),vjust=-0.5) + 
  scale_y_continuous(trans="log10",limits=c(0.5,1400)) + 
  theme_classic() +
  # Hide the X axis:
  theme(axis.line.x = element_blank()) +
  # Draw the new axis
  geom_hline()
print(graph)

The output:

Output for code above

Upvotes: 4

Related Questions