ggplot2 中堆叠条形图的颜色渐变
堆叠条形图默认使用基于色调的色标,以便区分条形图的不同部分。由于与我的堆栈相对应的因子水平是有序的,因此我想使用渐变比例。
这是一些虚构的问卷数据
dfr <- data.frame(
question = c("Do you like R?", "How about Stack Overflow?"),
rubbish = c(2, 1),
so.so = c(7, 9),
yippee = c(41, 40)
)
mdfr <- melt(dfr, measure.vars = c("rubbish", "so.so", "yippee"))
这是一个有效的图,但没有渐变色标
p1 <- ggplot(mdfr, aes(question, value, fill = variable)) +
geom_bar(position = "stack") +
coord_flip()
如果我添加渐变标度,我会被告知我应该使用数值变量,而不是分类变量。
p1 + scale_fill_gradient2()
#Error: Non-continuous variable supplied to scale_fill_gradient2.
如果我强制填充颜色变量为数字,那么 geom_bar 会抱怨它应该堆叠一个分类变量
ggplot(mdfr, aes(question, value, fill = as.integer(variable))) +
scale_fill_gradient2() +
geom_bar(position = "stack") +
coord_flip()
#Error in pmin(y, 0) : object 'y' not found
有没有办法解决这个问题?
编辑:
在思考这个问题之后,我认为手动秤可能是答案,但我也无法让它发挥作用。
cols <- c(rubbish = "red", so.so = "white", yippee = "blue")
p1 + scale_colour_manual(values = cols)
# Manual scale silently ignored
Stacked bar charts use a hue-based colour scale by default, in order to distinguish the different sections of bar. Since the factor levels corresponding to my stacks are ordered, I would like to use a gradient scale.
Here's some made-up questionnaire data
dfr <- data.frame(
question = c("Do you like R?", "How about Stack Overflow?"),
rubbish = c(2, 1),
so.so = c(7, 9),
yippee = c(41, 40)
)
mdfr <- melt(dfr, measure.vars = c("rubbish", "so.so", "yippee"))
Here's a plot that works, but without the gradient colour scale
p1 <- ggplot(mdfr, aes(question, value, fill = variable)) +
geom_bar(position = "stack") +
coord_flip()
If I add the gradient scale, I get told that I should be using a numerical variable for it, not categorical.
p1 + scale_fill_gradient2()
#Error: Non-continuous variable supplied to scale_fill_gradient2.
If I force the fill colour variable to be numerical, then geom_bar
complains that it should be stacking a categorical variable
ggplot(mdfr, aes(question, value, fill = as.integer(variable))) +
scale_fill_gradient2() +
geom_bar(position = "stack") +
coord_flip()
#Error in pmin(y, 0) : object 'y' not found
Is there a way round this?
EDIT:
After sleeping on the question, I thought a manual scale might be the answer, but I can't get that working either.
cols <- c(rubbish = "red", so.so = "white", yippee = "blue")
p1 + scale_colour_manual(values = cols)
# Manual scale silently ignored
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
哈德利的建议有效。
Hadley's suggestion works.
您可能想尝试:
scale_fill_brewer(palette="RdYlGn")
。我正在做类似的代码,但手册效果不佳。
通过此
scale_fill_brewer
,您可以使用调色板颜色:RdYlGn、红色等You might wanna try:
scale_fill_brewer(palette="RdYlGn")
.I'm doing a similar code and manual isn't working very well.
With this
scale_fill_brewer
you can use palette colors: RdYlGn, Reds, etc