更改特定变量 R ggplot 堆积条形图的颜色
Change color for specific variable R ggplot Stacked Bar chart
我正在尝试将颜色更改为 ggplot
中 stacked bar chart
中的特定变量。
我找到了 link,但这不是我想要的。
我想把Brand7
颜色改成黑色,但其他品牌应该用不同的随机颜色上色。
我想要的是为一个特定品牌使用某种条件 select 颜色,其他品牌可以像以前一样。
我还附上了可重现的例子。
set.seed(1992)
n=8
Category <- sample(c("Car", "Bus", "Bike"), n, replace = TRUE, prob = NULL)
Brand <- sample("Brand", n, replace = TRUE, prob = NULL)
Brand <- paste0(Brand, sample(1:14, n, replace = TRUE, prob = NULL))
USD <- abs(rnorm(n))*100
df <- data.frame(Category, Brand, USD)
ggplot(df, aes(x=Category, y=USD, fill=Brand)) +
geom_bar(stat='identity')
您可以使用类似这样的方法,访问标准的 ggplot-colours 并替换您需要的颜色。
访问 ggplot-colors 的函数,source
gg_color_hue <- function(n) {
hues = seq(15, 375, length=n+1)
hcl(h=hues, l=65, c=100)[1:n]
}
#make custom palette
mycols <- gg_color_hue(length(unique(df$Brand)))
names(mycols) <- unique(df$Brand)
mycols["Brand7"] <- "black"
#use palette in scale_fill_manual
ggplot(df, aes(x=Category, y=USD, fill=Brand)) +
geom_bar(stat='identity')+
scale_fill_manual(values=mycols)
我正在尝试将颜色更改为 ggplot
中 stacked bar chart
中的特定变量。
我找到了 link,但这不是我想要的。
我想把Brand7
颜色改成黑色,但其他品牌应该用不同的随机颜色上色。
我想要的是为一个特定品牌使用某种条件 select 颜色,其他品牌可以像以前一样。
我还附上了可重现的例子。
set.seed(1992)
n=8
Category <- sample(c("Car", "Bus", "Bike"), n, replace = TRUE, prob = NULL)
Brand <- sample("Brand", n, replace = TRUE, prob = NULL)
Brand <- paste0(Brand, sample(1:14, n, replace = TRUE, prob = NULL))
USD <- abs(rnorm(n))*100
df <- data.frame(Category, Brand, USD)
ggplot(df, aes(x=Category, y=USD, fill=Brand)) +
geom_bar(stat='identity')
您可以使用类似这样的方法,访问标准的 ggplot-colours 并替换您需要的颜色。
访问 ggplot-colors 的函数,source
gg_color_hue <- function(n) {
hues = seq(15, 375, length=n+1)
hcl(h=hues, l=65, c=100)[1:n]
}
#make custom palette
mycols <- gg_color_hue(length(unique(df$Brand)))
names(mycols) <- unique(df$Brand)
mycols["Brand7"] <- "black"
#use palette in scale_fill_manual
ggplot(df, aes(x=Category, y=USD, fill=Brand)) +
geom_bar(stat='identity')+
scale_fill_manual(values=mycols)