如何手动填充颜色的柱状图GGPLOT2(How to manually fill colors in

2019-06-23 09:51发布

我生成柱状图,我想以色某些群体与特定的颜色。 这里是我的直方图:

我有14组和我想颜色的第一红7,下4个蓝色和最后3橙色。 我怎样才能做到这一点ggplot? 谢谢。

Answer 1:

更新后的版本

无需指定分组列, 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)



文章来源: How to manually fill colors in a ggplot2 histogram
标签: r ggplot2