Reza
Reza

Reputation: 398

How to draw a logarithmic plot with ggplot2 when the numbers are smaller than 1?

I have a frequency distribution with a long tail and to make better use of the plot real state I draw a logarithmic plot. (The data below is for the sake of presentation)

freqs=c(0.7, 0.2, 0.05, 0.01, 0.001)
x=0:(length(freqs)-1)

df=data.frame(x=x, y=freqs)

library("ggplot2")

ggplot(df)  + 
geom_bar(mapping = aes(x = x, y = y),stat =   "identity")+ scale_y_log10() 

But then since the numbers are smaller than one, the logarithms will be negative and so the bars are upside down. Any way to go around this?

Upvotes: 1

Views: 931

Answers (1)

Marco Sandri
Marco Sandri

Reputation: 24272

An interesting solution is based on the use of geom_segment as suggested here.

freqs <- c(0.7, 0.2, 0.05, 0.01, 0.001)
x <- 0:(length(freqs)-1)
df <- data.frame(x=x, y=freqs)

library(ggplot2)
ggplot(df) + 
geom_segment(aes(x=x, xend=x, y=1e-4, yend=y), size=35, col="gray30") + 
scale_y_log10(breaks=c(0.001,0.01,0.1,1))+ ylab("")+ xlab("") +
scale_x_discrete(limits=c(-.5,4.5)) 

enter image description here

Upvotes: 1

Related Questions