Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
537 views
in Technique[技术] by (71.8m points)

r - How to manually fill colors in a ggplot2 histogram

I am generating a histogram and I would like to color certain groups with specific colors. Here is my histogram:

enter image description here

I have 14 groups and I would like to color the first 7 red, the next 4 blue, and the final 3 orange. How can I do this in ggplot? Thanks.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

UPDATED VERSION

No need to specify grouping column, ggplot command is much more compact.

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)

enter image description here

OLD VERSION

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)

enter image description here


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...