【问题标题】:How to specify a different colour for each panel in a multipanel plot in R如何在R中的多面板图中为每个面板指定不同的颜色
【发布时间】:2014-06-28 22:57:36
【问题描述】:

我使用 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")))

我尝试按照此处R: specifying color for different facets / panels in lattice 的相关问题中的建议将as.table=TRUE, groups=year, col=c("red", "blue", "green", "purple") 添加到代码中,但所做的只是在每个面板内而不是在面板之间交替条形的颜色。

任何有关如何解决此问题的建议将不胜感激!

如果可能的话,我也想知道如何在每个面板上方的条上实现类似的效果(即是否可以单独设置每个面板条的背景,而不仅仅是为整个情节中的所有面板设置?)

非常感谢!

【问题讨论】:

    标签: r plot panel histogram lattice


    【解决方案1】:

    这是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
        }
    ))
    

    【讨论】:

    • @约翰:非常感谢。这很棒!正是我想要的。谢谢!
    【解决方案2】:

    您可以尝试ggplot 替代方案:

    library(ggplot2)
    ggplot(data = df, aes(x = Para, fill = factor(Year))) +
      geom_histogram() +
      facet_wrap(~ Year) +
      scale_fill_manual(values = c("red", "blue", "green", "purple"))
    

    要按年份为条带背景着色,您可以查看here 以获得一些想法。

    【讨论】:

    • @Henrik:非常感谢您的回答!但是,如果有办法,我真的很想使用 lattice 包来实现这一点?
    • @Emily,我相信您可以使用lattice 制作所需的情节。但是,我不知道lattice 可以帮助你,对不起......
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多