首页 文章

如何使用ggplot绘制色轮?

提问于
浏览
9

我正在读这本书"ggplot2 - Elegant Graphics for Data Analysis"(Wickham,2009),"Scaling"(第32页)一节说:

缩放然后涉及将数据值映射到此空间中的点 . 有很多方法可以做到这一点,但是由于cyl是一个分类变量,我们将值映射到色轮上均匀分布的色调,如图3.4所示 . 当变量是连续的时,使用不同的映射 . 这些转换的结果是表3.4,其中包含对计算机有意义的值 .

enter image description here

enter image description here

这本书没有详细解释如何获得这个表3.4,更不用说图3.4了 . 内置数据库是 mpg . 任何人都知道如何获得此表和图表?提前致谢 .

2 回答

  • 11

    想知道如何在没有 coord_polar() 的情况下这样做,因为Wickham的书中的例子显然没有 . 事实证明你可以使用 geom_point(...) .

    library(ggplot2)
    r  <- seq(0,1,length=201)
    th <- seq(0,2*pi, length=201)
    d  <- expand.grid(r=r,th=th)
    gg <- with(d,data.frame(d,x=r*sin(th),y=r*cos(th),
                            z=hcl(h=360*th/(2*pi),c=100*r, l=65)))
    ggplot(gg) +
      geom_point(aes(x,y, color=z), size=3)+
      scale_color_identity()+labs(x="",y="") +
      coord_fixed()
    

    这会在几秒钟内呈现 . This reference表示默认亮度,l = 65 .

  • 9

    这接近你正在寻找的东西,但颜色过渡可能不够平滑 . 希望其他人可以改进:

    代码改编自here .

    # Create hsv grid
    d = expand.grid(h=seq(0,1,0.01), s=seq(0,1,0.05), v=1)
    
    p1 = ggplot() +
              coord_polar(theta="x") +
              scale_x_continuous(breaks=NULL) +
              scale_y_continuous(breaks=NULL) +
              scale_fill_identity() +
              geom_rect(data=d, mapping=aes(xmin=h, xmax=h+resolution(h), 
                                            ymin=s, ymax=s+resolution(s), 
                                            fill=hsv(h,s,v)))
    

    通过为 hs 值使用更精细的网格,您可以获得更平滑的颜色过渡,但渲染绘图需要很长时间 . 您可以通过将 v 的值设置为0到1来更改亮度 . (Per @BrodieG 's comment, set v=1/2 to get the brightness level of the figure in Hadley' s ggplot2 book . )

    下面是 h 值的步长为0.001的图表版本(同时将 s 步长保持为0.05) . 这需要几分钟才能在我相对较新的Macbook Pro上渲染,但沿着 h 坐标的过渡非常平滑:

    png("Colour wheel.png", 2000, 2000) 
    p1
    dev.off()
    

    enter image description here

    要获取颜色表,可以使用 hsv() 函数,该函数返回十六进制颜色值 . 例如:

    # Make up some hsv colors
    colors = data.frame(h=seq(0.1,0.5,length.out=6), 
                        s=seq(0.5,0.9,length.out=6), 
                        v=c(.5,.5,.5,.9,.9,.9))
    
    # Convert to hexadecimal
    apply(colors, 1, function(x) hsv(x[1],x[2],x[3]))
    [1] "#806640" "#7A8036" "#50802B" "#3CE642" "#29E68B" "#17E6E6"
    
    # Plot them to see what they look like
    plot(1:6,rep(1,6), pch=15, cex=5, col=apply(colors, 1, function(x) hsv(x[1],x[2],x[3])))
    

相关问题