我想分别在条形图上定义每个数据点的颜色,以在条形图上添加额外的信息层。我找不到解决方案
我知道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)
让我们说,我想用红色,非素数为蓝色的素数。甚至是奇怪的。
最通用解决方案将采用与输入相同维度的颜色列表,其中每个值定义绘制的相应数据点的颜色。
答案 0 :(得分:0)
这是一个可用于解决类似问题的解决方案。简而言之,您绘制条形图,使用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 :(得分:0)
然后,逐个绘制它们仍然更简单,并使用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)
答案 2 :(得分:0)
在将带状图用于多个组时,可以使用公式界面,只需在现有图上添加一个附加的带状图即可。但是,如果使用抖动,则无济于事。
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)