如何在ggplot中基于Y轴分配色阶 [英] How to assign a Colour Scale based on Y-axis in ggplot
问题描述
我正在尝试根据收入的y轴值为一些小提琴图分配颜色比例/渐变.但是,我只能得到白色的小提琴图.我可以根据state.region而不是Income更改颜色.
I am trying to assign a colour scale/gradient to some violin plots based on the y-axis value of Income. However, I only get a white violin plot. I can change the colour based on state.region but not Income.
数据
USA.states <- data.frame(state.region,state.x77)
代码
p <- ggplot(USA.states,aes(x=state.region,y=Income,fill=Income))+
geom_violin(trim = F,)+
ggtitle("Violin plot of income and Population")
p + scale_fill_gradient(low="red",high="blue")
我将 fill
分配给了 Income
,但最终以白色填充.
I assigned the fill
to Income
but it just ends up filled with white.
推荐答案
您可以根据分段创建伪填充,也可以直接根据基础数据(在ggplot_built对象中)创建分段.
You can create a pseudo-fill from segments, and you can create those from the underlying data (in the ggplot_built object) directly.
如果需要其他多边形轮廓,则仍然需要使用为线段计算的x和y坐标手动创建多边形.(将其放入数据框肯定比下面更聪明,因此请不要将此当作福音.)
If you want an additional polygon outline, you would still need to create the polygons manually though, using x and y coordinates as calculated for the segments. (There is certainly a cleverer way to put this into a data frame than below, so don't take this as gospel).
还有一点需要注意,原始情节中的小提琴似乎是按比例缩放的,但是我不完全了解如何缩放,因此我只是用一个常数进行了缩放,这是我通过反复试验发现的.
Of another note, the violins in the original plot seem to be scaled, but I don't exactly understand how, so I just scaled it with a constant which I found with some trial and error.
library(tidyverse)
USA.states <- data.frame(state.region,state.x77)
p <- ggplot(USA.states,aes(x=state.region,y=Income,fill=Income))+
geom_violin(trim = F)
mywidth <- .35 # bit of trial and error
# This is all you need for the fill:
vl_fill <- data.frame(ggplot_build(p)$data) %>%
mutate(xnew = x- mywidth*violinwidth, xend = x+ mywidth*violinwidth)
# Bit convoluted for the outline, need to be rearranged: the order matters
vl_poly <-
vl_fill %>%
select(xnew, xend, y, group) %>%
pivot_longer(-c(y, group), names_to = "oldx", values_to = "x") %>%
arrange(y) %>%
split(., .$oldx) %>%
map(., function(x) {
if(all(x$oldx == "xnew")) x <- arrange(x, desc(y))
x
}) %>%
bind_rows()
ggplot() +
geom_polygon(data = vl_poly, aes(x, y, group = group),
color= "black", size = 1, fill = NA) +
geom_segment(data = vl_fill, aes(x = xnew, xend = xend, y = y, yend = y,
color = y))
由 reprex程序包(v1.0.0)创建于2021-04-14 sup>
Created on 2021-04-14 by the reprex package (v1.0.0)
这篇关于如何在ggplot中基于Y轴分配色阶的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!