ggplot直方图中的颜色填充渐变

时间:2016-04-15 17:11:26

标签: r ggplot2 colors

我想将颜色填充渐变更改为类似于库中的“光谱”(RColorBrewer)以匹配我正在使用的其他图形。任何建议将不胜感激

d$Age<-c(28.0, 40.0,   NA,   NA, 38.0, 58.0,   NA, 51.0, 59.0, 91.0, 46.0, 58.0, 22.0, 58.0, 41.0, 63.0, 53.0, 58.0, 39.0,34.0, 91.0, 41.0, 40.0, 70.0, 40.0, 53.0, 61.0, 29.0,   NA, 34.5, 50.0, 64.0, 91.0, 37.0, 60.0, 68.0, 55.0, 55.0,52.0,   NA, 28.0, 45.0, 33.0, 41.0, 66.0,   NA, 30.0, 49.0, 55.0, 38.0)

#Plot the histogram of Age
ggplot(data=d, aes(d$Age)) + 
  geom_histogram(breaks=seq(0, 105, by =5), 
                 col="red", 
                 aes(fill=..count..)) + 
  labs(title="Histogram for Age") + 
  labs(x="Age", y="Count") + 
  xlim(c(0,105)) + 
  scale_fill_gradient("Count", low = "blue", high = "red")

2 个答案:

答案 0 :(得分:3)

您可以使用?scale_fill_distiller

library("ggplot2")

d <- data.frame(Age = c(28.0, 40.0,   NA,   NA, 38.0, 58.0,   NA, 51.0, 59.0, 91.0, 46.0, 58.0, 22.0, 58.0, 41.0, 63.0, 53.0, 58.0, 39.0,34.0, 91.0, 41.0, 40.0, 70.0, 40.0, 53.0, 61.0, 29.0,   NA, 34.5, 50.0, 64.0, 91.0, 37.0, 60.0, 68.0, 55.0, 55.0,52.0,   NA, 28.0, 45.0, 33.0, 41.0, 66.0,   NA, 30.0, 49.0, 55.0, 38.0))

ggplot(data=d, aes(Age)) + 
  geom_histogram(breaks=seq(0, 105, by =5), 
                 col="red", 
                 aes(fill=..count..)) + 
  labs(title="Histogram for Age") + 
  labs(x="Age", y="Count") + 
  xlim(c(0,105)) + 
  scale_fill_distiller(palette = "Spectral")

链接到文档http://docs.ggplot2.org/current/scale_brewer.html

答案 1 :(得分:0)

使用此

#Plot the histogram of Age
> ggplot(data=d, aes(d$Age)) + 
+   geom_histogram(breaks=seq(0, 105, by =5), 
+                  col="red", 
+                  aes(fill=..count..))+labs(title="Histogram for Age") + labs(x="Age", y="Count")+ xlim(c(0,105))  + scale_fill_distiller(labels=comma,palette = "Spectral")