如何在ggplot2直方图中手动填充颜色 [英] How to manually fill colors in a ggplot2 histogram
本文介绍了如何在ggplot2直方图中手动填充颜色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在生成直方图,我想用特定颜色对某些组进行着色。这里是我的直方图:
我有14组,我想为前7个红色,后4个蓝色和最后3个橙色着色。我怎样才能在ggplot中做到这一点?感谢。
解决方案
更新版本 $ b 无需指定分组列, ggplot
命令更加紧凑。
<$ c $数据库(ggplot2)
set.seed(1234)
#数据生成块
df < - data.frame(x = sample(1:14,1000,替换= T))
#颜色
颜色< -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)
#
#数据生成块
#
df < - data.frame(x = sample(c(1:14),1000,replace )=
df $ group < - ifelse(df $ x <= 7,1,ifelse(df $ x <= 11,2,3))
#
#绘制
#
ggplot(df,aes(x = x))+
geom_histogram(data = subset(df,group == 2),fill =blue)+ $ b $ geom_histogram(data = subset(df,group == 1),fill =red)+
b geom_histogram(data = subset(df,group == 3),fill =orange)+
scale_x_discrete(breaks = df $ x,labels = df $ x)
I am generating a histogram and I would like to color certain groups with specific colors. Here is my histogram:
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.
解决方案
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)
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)
这篇关于如何在ggplot2直方图中手动填充颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文