【问题标题】:Define color for each datapoint in a stripchart separately分别为条形图中的每个数据点定义颜色
【发布时间】:2015-12-26 07:09:39
【问题描述】:

我想分别定义条形图上每个数据点的颜色,以便在条形图上添加额外的信息层。我没有找到解决办法

我知道Different coloring of groups in R plot,答案表明每个数据点都不可能。我说的对吗?

解决方法可能是在 for 循环中逐列绘制它,但随后 x 位置被搞砸了

d = c (1,3,4);
e = c (2,3,4)
f = c (2,6,5)
data = list (d, e, f)
stripchart (data, vertical =T, pch =21, bg = 1, col=2)

比方说,我想将素数涂成红色,将非素数涂成蓝色。或偶数和奇数。

通用的解决方案将采用与输入相同维度的颜色列表,其中每个值定义绘制的相应数据点的颜色。

【问题讨论】:

    标签: r plot colors stripchart


    【解决方案1】:

    这里有一个解决方案,您可以使用它来解决类似问题。简而言之,您绘制条形图,使用 gridGraphics 包将绘图转换为 grob,然后仅通过编辑 grob 来更改图形基元。

    library(gridGraphics)
    grid.newpage()
    
    # Get some data
    sample(x = 1:100, size = 50) -> data
    
    # Grab plot...Now it's a grob you can modify
    stripchart (data, vertical =T, pch =21, bg = 1, col=2)
    grid.echo()
    grid.grab() -> mygrob
    
    # Pull out the values of the data and strip unit class
    mygrob$children$`graphics-plot-1-points-1`$y -> myunits
    convertUnit(myunits, "native", valueOnly = TRUE) -> myunits
    
    # Some data to reference ours against...You can use a test for if your data is a prime, equal number, odd number, whatever..I'm just going to test if my data is in this vector and specify the color based on the results from this test.
    sample(1:100, size = 10) -> sampleVec
    ifelse(myunits %in% sampleVec, "red", "green") -> updatedCols
    
    # Now sub in the new color specs for the points
    mygrob$children$`graphics-plot-1-points-1`$gp$col <- updatedCols
    mygrob$children$`graphics-plot-1-points-1`$gp$fill <- updatedCols
    
    # ...And plot
    grid.draw(mygrob) 
    

    【讨论】:

    • 感谢@Chris,这有点太长了,但很高兴知道有人可以做到这一点!
    【解决方案2】:

    那么将它们一一绘制还是比较简单的,使用bg=参数:

    # generate fake data
    datalist = list( rnorm(100), rnorm(100, sd = 1),rnorm(100, sd = 2) )
    # generate color value for each data point  (say I want to color by each values sign +/-)
    colorlist = lapply(datalist, sign)
    plot(0,0,type="n",xlim=c(0.5,3.5), ylim=c(-10,10),  xaxt = 'n', xlab ="", ylab = "value",  main ="Smear")
    for (i in 1:3) { stripchart(na.omit(datalist[[i]]), at = i, add = T, bg = colorlist[[i]]+2, vertical = T, pch =21, method = "jitter") }
    axis(side=1,at=1:3,labels=3:1)
    

    【讨论】:

      【解决方案3】:

      当对多个组使用条形图时,使用公式界面,您可以在现有绘图中添加一个额外的条形图。但是,如果您使用抖动,那将无济于事。

      mydata <- data.frame (x = rnorm(30), group = gl(3, 10, labels = letters[1:3]))
      stripchart(x ~ group, data = mydata)
      makered <- mydata$group == "b" & mydata$x < 1
      stripchart(x ~ group, data = mydata[makered, ], col = "red", add = TRUE)
      

      【讨论】:

        猜你喜欢
        • 2021-09-24
        • 1970-01-01
        • 2015-05-14
        • 2019-10-27
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-04-09
        • 1970-01-01
        相关资源
        最近更新 更多