在此图形中,我希望秘鲁的列采用不同的颜色,以区别于其他国家。在这种情况下,“ pais”是包含“ Peru”的列。我使用pais $ Peru过滤了一行的国家(Peru),但它不起作用。我得到以下结果“ pais $ Peru中的错误:$运算符对于原子向量无效”
有人知道该怎么做吗?如何构建我的代码?
我的密码是
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))
THANKSSS
一种方法是使用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)
结果]