尝试在ggplot中的直方图上应用颜色渐变 [英] Trying to apply color gradient on histogram in ggplot

查看:2686
本文介绍了尝试在ggplot中的直方图上应用颜色渐变的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在ggplot中用颜色淹没了。我试图应用颜色渐变基于排名列下面。我很确定这是颜色和填充或离散和连续变量之间的差异。我想要的颜色如下图中c和d所示,但我最接近的尝试是e和f,其中点是有色的,但不是渐变的颜色。我喜欢的渐变适用于秩1:100的值,所有其他值的点为黑色。

I am floundering with colors in ggplot. I am trying to apply a color gradient based on the rank column below. I am pretty sure this is a discrepancy between color and fill or discrete and continuous variables. I want colors as shown on the scale in "c" and "d" below, but my closest attempts are "e" and "f" where the points are colored but not colored by gradient. The gradient I prefer applies to values of rank 1:100, with all others values' points black.

任何帮助将非常感激。

library(reshape2)
library(ggplot2)

co2 <- read.table(
  header=TRUE, text='
rank tons
1     2 1.00
2     4 1.00
3     7 0.00
4    44 0.00
5   104 0.00
6    48 0.05
7    32 0.50
8     5 0.00
9    78 1.00
10   12 0.00
11   15 0.00
12  176 1.00
13  440 0.02
14  249 0.00
15  481 0.00
16  388 0.00
17  458 0.05
18  488 0.00
19  264 0.00
20  203 0.00
            ')      

我试过:

#does not add rank as a color
c<- ggplot(data=co2, aes(x = tons, color=rank)) 
c + geom_dotplot(stackgroups = TRUE, binwidth = .05, binpositions = "all")  +
    scale_colour_gradient(limits=c(1, 500))

#also does not add rank as color
d<- ggplot(data=co2, aes(x = tons, color=rank)) 
d + geom_dotplot(stackgroups = TRUE, binwidth = 0.05, method = "histodot")  + 
    scale_colour_gradient(limits=c(1, 100))

#create breaks for fill-- works correctly but no gradient
co2$brks<- cut(co2$rank, c(seq(0, 100, 20), max(co2$rank)))
e<- ggplot(data=co2, aes(x = tons, fill=brks)) 
e + geom_dotplot(stackgroups = TRUE, binwidth = 0.05, method = "histodot")  

#also works correctly but no gradient
f<- ggplot(data=co2, aes(x = tons, fill=brks)) + geom_histogram() 
f 

我已经检查过这些,但是我仍然缺少一些东西:

I checked these already but I'm still missing something:

  • Color Gradients With ggplot
  • Use histogram breaks to apply function over second column
  • gradient breaks in a ggplot stat_bin2d plot
  • http://docs.ggplot2.org/current/geom_dotplot.html

推荐答案

这是一个hacky但它的工作原理:

This is a bit of a hacky answer, but it works:

##Define breaks
co2$brks<- cut(co2$rank, c(seq(0, 100, 5), max(co2$rank)))
#Create a plot object:
g = ggplot(data=co2, aes(x = tons, fill=brks)) +
   geom_dotplot(stackgroups = TRUE, binwidth = 0.05, method = "histodot")

现在我们手动指定要用作调色板的颜色:

Now we manually specify the colours to use as a palette:

 g + scale_fill_manual(values=colorRampPalette(c("white", "red"))( length(co2$brks) ))

这篇关于尝试在ggplot中的直方图上应用颜色渐变的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆