10

我正在生成一个直方图,我想用特定颜色为某些组着色。这是我的直方图:

在此处输入图像描述

我有 14 组,我想将前 7 组染成红色,接下来的 4 组染成蓝色,最后 3 组染成橙色。我怎样才能在ggplot中做到这一点?谢谢。

4

1 回答 1

16

更新后的版本

无需指定分组列,ggplot命令更紧凑。

library(ggplot2)
set.seed(1234)

# Data generating block
df <- data.frame(x=sample(1:14, 1000, replace=T))
# Colors
colors <- c(rep("red",7), rep("blue",4), rep("orange",3))

ggplot(df, aes(x=x)) +
  geom_histogram(fill=colors) +
  scale_x_discrete(limits=1:14)

在此处输入图像描述

旧版

library(ggplot2)

# 
# Data generating block
#
df <- data.frame(x=sample(c(1:14), 1000, replace=TRUE))
df$group <- ifelse(df$x<=7, 1, ifelse(df$x<=11, 2, 3))

#
# Plotting
#
ggplot(df, aes(x=x)) +
  geom_histogram(data=subset(df,group==1), fill="red") +
  geom_histogram(data=subset(df,group==2), fill="blue") +
  geom_histogram(data=subset(df,group==3), fill="orange") +
  scale_x_discrete(breaks=df$x, labels=df$x)

在此处输入图像描述

于 2012-11-21T22:10:14.287 回答