我目前在R中有这个条形图(用ggplot2
创建)
我需要这样:
我尝试使用RColorBrewer包,但它没有用,因为相应调色板中的最大颜色数量为11.任何想法?
pal <- brewer.pal(11,"RdYlGn")
ggplot(data = bm_mod, aes(x = bm_mod$country, y = bm_mod$V)) +
geom_bar(stat = "identity", colour = pal, fill = pal) + coord_flip() +
labs(y="Under/over valuation in %", x="")
以下是数据:link
更新: 我用这段代码再试一次:
ggplot(data = bm_mod, aes(x = country, y = V)) +
geom_bar(stat = "identity", fill = country, show_guide = FALSE) +
coord_flip() + scale_fill_manual(values = colorRampPalette(brewer.pal(11,"RdYlGn"))(nrow(bm_mod))) +
labs(y="Under/over valuation in %", x="")
然而输出看起来很奇怪。这是酿酒商的问题还是其他错误?
答案 0 :(得分:5)
几点:
正如尼克所说,你不应该使用bd_mod$
来引用aes()
内的变量。指定data = bm_mod
的重点是让您不必一次又一次地键入bm_mod$
。
其次,您设置fill = pal
的尝试有点混乱。指定aes()
之外的美学意味着您将设置为特定值,因此只应使用单个值来完成,例如fill = "blue"
。
您真正想要的是每个x值的不同填充,因此您应该映射填充到country
,然后在scale_fill_manual
中设置颜色方案。
当您提出类似这样的问题时,您应该始终提供可重复的示例。在这种情况下,这将是非常容易的,如下所示:
df <- data.frame(x = letters,y = runif(26))
ggplot(df,aes(x = x,y = y)) +
geom_bar(aes(fill = x),stat = "identity",show_guide = FALSE) +
scale_fill_manual(values = colorRampPalette(brewer.pal(11,"RdYlGn"))(26))
我使用colorRampPalette
来插入您想要使用的brewer调色板中的颜色。
答案 1 :(得分:3)
以下是假数据的示例。 Henrik指出,你需要在美学中指定fill=V
。然后你需要scale_fill_XXXX
件来指定你想要使用的色标。
require(ggplot2)
set.seed(100)
fake.data = data.frame(country = LETTERS, V = runif(26, -40, 40))
fake.data$country = factor(LETTERS, LETTERS[order(fake.data$V)]) # reorder factors
ggplot(data = fake.data, aes(x = country, y = V, fill = V)) +
geom_bar(stat = "identity") +
scale_fill_gradient2(low="red", mid="yellow", high="green") +
coord_flip() +
labs(y="Under/over valuation in %", x="")
产生以下情节:
答案 2 :(得分:0)
足以定义11个区间并为它们分配颜色?试试这个:
intervals <- cut(bm_mod$V, 11)
ggplot(data=bm_mod, aes(x=country, y=V)) +
geom_bar(stat="identity", colour=pal[intervals], fill=pal[intervals]) +
coord_flip() + labs(y="Under/over valuation in %", x="")