r - 如何使用ggplot2将光栅文件绘制为直方图?

标签 r ggplot2 histogram raster

我有一个光栅文件
我想绘制为直方图,我使用 hist() 进行了绘制,如下所示。但我想使用 ggplot2 进行绘图,以更好的方式绘制它以供发布。

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))

我试过这个:
  qplot(rating, data=r, geom="histogram")

错误:
            ggplot2 doesn't know how to deal with data of class RasterLayer

我需要绘制类似的东西:

http://docs.ggplot2.org/0.9.3/geom_histogram-28.png

最佳答案

作为快速解决方案您可以使用 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:也许你需要使用scale_x_discrete获得更好的轴外观

编辑 添加渐变填充
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

enter image description here

关于r - 如何使用ggplot2将光栅文件绘制为直方图?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14668096/

相关文章:

r - 用 ID 列展平数据框中的列表列

java - 如何从 RCaller java 调用 R 脚本文件?

python - 导出 sklearn 模型以在 R 中运行

R:来自 ggmap 的 get_map()/get_googlemap() 错误

c++ - 如何计算 OpenCV C++ 中按列聚合的亮度直方图

r - 从 DocumentDB 导入到 Azure 机器学习 - 以毫秒为单位的日期时间

r - 创建后修改ggplot对象

r - 垂直对齐 geom_label 元素

python - seaborn 中的直方图 bin 大小

python - 如何在带有子图的绘图中设置辅助x轴及其范围?