分别为带状图中的每个数据点定义颜色

Define color for each datapoint in a stripchart separately

我想分别定义带状图上每个数据点的颜色,以在带状图上添加额外的信息层。我没有找到解决方案

我知道 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)

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

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

这是一个解决类似问题的方法。简而言之,您绘制带状图,使用 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) 

那么1个1个画出来还是比较简单的,使用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)

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

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)