我使用 R 中的 lattice 包创建了一个多面板图,代码如下。该图有四个面板,每个面板包含一个直方图。我希望每个面板中的条形都是一种独特的颜色,但我很难做到这一点。
Para = as.vector(rnorm(100, mean=180, sd=35))
Year = as.vector(c(rep(1,25),rep(2,25),rep(3,25), rep(4,25)))
df = as.data.frame(cbind(Para, Year))
library(lattice)
print(histogram(~ Para | Year, data = df, scales = list(cex = c(1.0, 1.0)),
layout = c(4, 1), type = "count",
xlab = list("Parameter", fontsize = 16),
ylab = list("Frequency", fontsize = 16),
strip = function(bg = 'white',...) strip.default(bg = 'white', ...),
breaks = seq(0, 300, by = 50), ylim = seq(0, 35, by = 10),
as.table = TRUE, groups = year, col = c("red", "blue", "green", "purple")))
我尝试按照建议将 as.table=TRUE, groups=year, col=c("red", "blue", "green", "purple")
添加到代码中在这里找到一个相关问题 R: specifying color for different facets / panels in lattice , 但所有这些所做的只是在每个面板内而不是在面板之间交替显示条形的颜色。
任何有关如何解决此问题的建议将不胜感激!
如果可能的话,我还想知道如何在每个面板上方的 strip 上实现类似的效果(即是否可以单独设置每个面板 strip 的背景,而不是只为整个图中的所有面板设置背景?)
非常感谢!
最佳答案
这是lattice
版本。本质上,您定义了一个颜色向量,这是我在 histogram()
函数之外完成的。在 histogram()
函数中,您使用了一个 panel.function
,它允许您使每个面板看起来不同。您调用 panel.histogram
并告诉它根据 packet.number()
选择一种颜色。该函数仅返回一个整数,指示正在绘制哪个面板,面板 1 变为红色,面板 2 变为蓝色等。
Para = as.vector(rnorm(100, mean=180, sd=35))
Year = as.vector(c(rep(1,25),rep(2,25),rep(3,25), rep(4,25)))
df = as.data.frame(cbind(Para,Year))
colors<-c("red","blue","green","purple") #Define colors for the histograms
print(histogram(~Para | Year, data = df, scales=list(cex=c(1.0,1.0)),
layout=c(4,1), type="count", xlab=list("Parameter", fontsize=16),
ylab=list("Frequency", fontsize=16),
strip=function(bg='white',...) strip.default(bg='white',...),
breaks=seq(0,300, by=50), ylim=seq(0,35,by=10),
as.table=TRUE, groups=Year,col=colors, #passing your colors to col
panel=function(x, col=col,...){
panel.histogram(x,col=col[packet.number()],...) #gets color for each panel
}
))
关于r - 如何在 R 中的多面板图中为每个面板指定不同的颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23594480/