如何在R中创建具有不同颜色的n个绘图?

时间:2018-01-28 02:37:18

标签: r ggplot2

所以我试图在R中绘制数据帧的所有数字列的直方图。我正在使用for {循环中的ggplot2进行绘图。我想要的是为不同列的直方图提供不同的颜色。

以下是可重现的代码:

library("ggplot2")
library("MASS")
library("corrplot")

data(Boston)

#Data Reading
Boston <- Boston
names(Boston)
#[1] "crim"    "zn"      "indus"   "chas"    "nox"     "rm"      "age"     "dis"     "rad"     "tax"     "ptratio"
#[12] "black"   "lstat"   "medv"

#Getting idea of the data
summary(Boston)
str(Boston)

#Random sampling
index <- sample(1:nrow(Boston), floor(0.8 * nrow(Boston)), replace = FALSE)
training <- Boston[index,]
testing <- Boston[-index,]

#Exploratory Analysis
col = rainbow(ncol(Boston))

#1) Histogram
for (i in 1:ncol(training)) {
  if(is.numeric(training[, i])){
    print(
      ggplot(data = data.frame(training[, i]), aes(x = data.frame(training[,i]), fill = col[i])) + 
        geom_histogram(bins = 10) + 
        ggtitle(paste0(names(training)[i])) + 
        theme(plot.title = element_text(hjust = 0.5)) + 
        labs(x = ""))
  }
}

我想要不同的颜色,以使其在视觉上更具吸引力。

2 个答案:

答案 0 :(得分:2)

数据:

data(Boston)
set.seed(1L) # set random seed
index <- sample(1:nrow(Boston), floor(0.8 * nrow(Boston)), replace = FALSE)
training <- Boston[index,]

<强>代码:

# 1. individual plots

# select numeric and integer type columns
training <- training[, sapply( training, class) %in% c( "numeric", "integer")]
# define colors for columns
col_train <- setNames( rainbow(ncol(Boston)), nm = colnames(training) )
# get ggplot structure for each column
plot_list <- lapply( names( col_train ), function(x){
  ggplot(data = NULL) + 
    geom_histogram(mapping = aes(x = training[, x, drop = TRUE ]), 
                   fill = col_train[ x ],
                   bins = 10) +
    ggtitle(x) + 
    theme(plot.title = element_text(hjust = 0.5)) + 
    labs(x = "")
})
# assign names
names(plot_list) <- names(col_train)
# print plots
print(plot_list)
# print chas
print(plot_list["chas"])
# print first plot
print(plot_list[[1]])

enter image description here

# 2. plots combined in a single window  

library(reshape2)
training <- melt( training )  # melt training data

library(ggplot2)
ggplot(data = training, aes(value, fill = variable)) + 
  geom_histogram(bins = 10)

enter image description here

ggplot(data = training, aes(value, fill = variable)) + 
  geom_histogram(bins = 10) + 
  facet_wrap(~ variable, scales = "free_x")

enter image description here

答案 1 :(得分:1)

尝试将fill = col[i]aes电话中的ggplot功能移至geom_histogram电话内。

#1) Histogram
for (i in 1:ncol(training)) {
      if(is.numeric(training[, i])){
        print(
          ggplot(data = data.frame(training[, i]), aes(x = 
            data.frame(training[,i]))) + 
            geom_histogram(bins = 10, fill = col[i]) + 
            ggtitle(paste0(names(training)[i])) + 
            theme(plot.title = element_text(hjust = 0.5)) + 
            labs(x = ""))
      }
}