【发布时间】:2016-06-06 10:11:56
【问题描述】:
我正在尝试在下面创建的 ggplot2 中显示颜色渐变。所以使用以下数据和代码
vector <- c(9, 10, 6, 5, 5)
Names <- c("Leadership", "Management\n", "Problem Solving",
"Decision Making\n", "Social Skills")
# add \n
Names[seq(2, length(Names), 2)] <- paste0("\n" ,Names[seq(2, length(Names), 2)])
# data.frame, including a grouping vector
d <- data.frame(Names, vector, group=c(rep("Intra-capacity", 3), rep("Inter-capacity", 2)))
# correct order
d$Names <- factor(d$Names, levels= unique(d$Names))
d$group_f = factor(d$group, levels=c('Intra-capacity','Inter-capacity'))
# plot the bars
p <- ggplot(d, aes(x= Names, y= vector, group= group, fill=vector, order=vector)) +
geom_bar(stat= "identity") +
theme_bw()+
scale_fill_gradient(low="white",high="blue")
# use facet_grid for the groups
#p + facet_grid(.~group_f, scales= "free_x", space= "free_x")
p+ theme(text = element_text(size=23),plot.background = element_rect(fill = "white"),
strip.background = element_rect(fill="Dodger Blue")) +
facet_grid(.~group_f, scales= "free_x", space= "free_x") + xlab("") +ylab("") +
theme(strip.text.x = element_text(size = 18, colour = "white" )) +
geom_text(size=10, aes(label=vector))
但现在我想插入颜色渐变,以便每个矩形看起来像下图(我想要的输出):
我也看过这个:
R: gradient fill for geom_rect in ggplot2
create an arrow with gradient color
Label minimum and maximum of scale fill gradient legend with text: ggplot2
How can I apply a gradient fill to a geom_rect object in ggplot2?
还尝试使用:
scale_fill_gradient(low="white",high="blue") 或
scale_fill_gradientn(colours = c("blue","white","red"),
values = c(0,5,10),
guide = "colorbar", limits=c(0,10))
但我显然做错了什么。
【问题讨论】:
-
好奇心占了上风,我不得不问。这个梯度的附加值是多少?请注意,为了使渐变起作用,它们需要映射到一个变量。
-
@RomanLuštrik 我的导师希望我这样做。
-
这不是一个有效的统计原因。请推荐您的导师参加 Batagelj 的关于墨信息比的讲座,这是统计学博士生的必修课。
-
让我说得更具体一些。我导师的客户希望在他们的报告中包含它,他们评估一些特定的组件并基于他们绘制矩形的值。但是,如果可能的话,并且你知道如何,那就太好了。
-
据我所知,开箱即用的 ggplot2 无法做到这一点。您可以通过某种渐变颜色(映射到上面提到的值)为整个列着色。这样做的一个hacky方法是创建多边形并用渐变填充它们(参见post)。另一种方法是在 Gimp2/Inkscape 中修改您现有的图形。