I have a raster file and I want to plot as a histogram ,i did it using hist() as shown below. but i would like to plot using ggplot2 which plot it in a better way for publication.
conne <- file("C:\\fined.bin","rb")
r = raster(y)
hist(r, breaks=30, main="SMD_2010",
xlab="Pearson correlation", ylab="Frequency", xlim=c(-1,1))
I tried this:
qplot(rating, data=r, geom="histogram")
Error:
ggplot2 doesn't know how to deal with data of class RasterLayer
I need to plot something like:
http://docs.ggplot2.org/0.9.3/geom_histogram-28.png
As a fast solution You can use the result of hist
f <- hist(r, breaks=30)
dat <- data.frame(counts= f$counts,breaks = f$mids)
ggplot(dat, aes(x = breaks, y = counts)) +
geom_bar(stat = "identity",fill='blue',alpha = 0.8)+
xlab("Pearson correlation")+ ylab("Frequency")+
scale_x_continuous(breaks = seq(-1,1,0.25), ## without this you will get the same scale
labels = seq(-1,1,0.25)) ## as hist (question picture)
PS : Maybe you need to use scale_x_discrete to get better axis look
EDIT to add gradient fill
ggplot(dat, aes(x = breaks, y = counts, fill =counts)) + ## Note the new aes fill here
geom_bar(stat = "identity",alpha = 0.8)+
xlab("Pearson correlation")+ ylab("Frequency")+
scale_x_continuous(breaks = seq(-1,1,0.25),
labels = seq(-1,1,0.25))+
scale_fill_gradient(low="blue", high="red") ## to play with colors limits

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With