r - 如何在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")
我将其分配fill
给Income
但它最终充满了白色。
解决方案
您可以从段创建伪填充,并且可以直接从基础数据(在 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)
推荐阅读
- flutter - 类型'Null'不是颤振布尔表达式中的'bool'
- mongodb - 如何更改在 ECS 上运行的 mongo 的配置文件
- php - 产品自定义分类术语循环 - 图像的 src 为空
- r - 根据 r 中的其他列对一个列表中的一列的所有值进行分组
- python - 合并两个共享相同列值的数据框
- html - -1 的 tabIndex 是否与没有 tabIndex 相同,还是应该使用 undefined 或 null?
- php - 覆盖“porto”架构中的类
- artifactory - Artifactory 服务器抛出错误:服务不可用
- dictionary - pl/sql中使用数字作为索引的键值映射
- airflow - 在气流传感器中使用 XCom