如何使用 R 中的 geom_bar 为不同颜色的一列(数据框中的值属于一行)着色(填充)?
How to color (fill in) just one column (whose value in the data frame belongs to a row) of different colors using geom_bar in R?
在此图形中,我希望秘鲁的列显示不同的颜色,以区别于其他国家。在本例中,"pais" 是包含 "Peru" 的列。我使用 pais$Peru 来过滤连续的国家(秘鲁),但它不起作用。我得到以下结果 "Error in pais$Peru : $ operator is invalid for atomic vectors"
有人知道怎么做吗?如何构建我的代码?
我的代码是
ggplot() + geom_bar(aes(y = railroad,
x=reorder(pais, -railroad),
fill=pais$Peru),
data = jaja,
stat = "identity")+
guides(fill=FALSE)+
xlab(NULL)+ ylab(NULL)+
scale_y_continuous(limit = c(0,7))+ theme(axis.text.x = element_text(angle = 50))
感谢
一种方法是使用 scale_fill_manual
并传递带有国家和颜色的命名向量。
一个例子:
library(ggplot2)
library(tidyverse)
df <- mtcars %>%
group_by(cyl) %>%
summarise(avg_hp = mean(hp))
# Create named vector to pass to scale_fill_manual
# Color of green for cyl of 4
# Default of 'blue' where cyl doesn't equal 4
bar_colors <- c('4' = 'green' ,setNames(rep(c('blue'), times = length(df[df$cyl!=4,]$cyl)), df[df$cyl!=4,]$cyl))
ggplot(df, aes(x= factor(cyl), y = avg_hp, fill = factor(cyl))) +
geom_bar(stat = 'identity') +
scale_fill_manual(values = bar_colors)
结果
在此图形中,我希望秘鲁的列显示不同的颜色,以区别于其他国家。在本例中,"pais" 是包含 "Peru" 的列。我使用 pais$Peru 来过滤连续的国家(秘鲁),但它不起作用。我得到以下结果 "Error in pais$Peru : $ operator is invalid for atomic vectors"
有人知道怎么做吗?如何构建我的代码?
我的代码是
ggplot() + geom_bar(aes(y = railroad,
x=reorder(pais, -railroad),
fill=pais$Peru),
data = jaja,
stat = "identity")+
guides(fill=FALSE)+
xlab(NULL)+ ylab(NULL)+
scale_y_continuous(limit = c(0,7))+ theme(axis.text.x = element_text(angle = 50))
感谢
一种方法是使用 scale_fill_manual
并传递带有国家和颜色的命名向量。
一个例子:
library(ggplot2)
library(tidyverse)
df <- mtcars %>%
group_by(cyl) %>%
summarise(avg_hp = mean(hp))
# Create named vector to pass to scale_fill_manual
# Color of green for cyl of 4
# Default of 'blue' where cyl doesn't equal 4
bar_colors <- c('4' = 'green' ,setNames(rep(c('blue'), times = length(df[df$cyl!=4,]$cyl)), df[df$cyl!=4,]$cyl))
ggplot(df, aes(x= factor(cyl), y = avg_hp, fill = factor(cyl))) +
geom_bar(stat = 'identity') +
scale_fill_manual(values = bar_colors)
结果