首页 > 解决方案 > 如何在ggplot中基于​​Y轴分配色标

问题描述

我正在尝试根据收入的 y 轴值为一些小提琴图分配色阶/渐变。但是,我只得到一个白色小提琴情节。我可以根据 state.region 更改颜色,但不能根据收入更改颜色。

数据

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")

我将其分配fillIncome但它最终充满了白色。

标签: rggplot2

解决方案


您可以从段创建伪填充,并且可以直接从基础数据(在 ggplot_built 对象中)创建这些。

如果您想要一个额外的多边形轮廓,您仍然需要手动创建多边形,使用为线段计算的 x 和 y 坐标。(当然有比下面更聪明的方法将它放入数据框中,所以不要把它当作福音)。

另一个值得注意的是,原始情节中的小提琴似乎是按比例缩放的,但我不完全理解如何缩放,所以我只是用一个常数缩放它,我通过一些试验和错误发现。

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 包于 2021-04-14 创建(v1.0.0)


推荐阅读