[英]stacked geom_bar without aggregating the fill values results in incorrect axis values
我正在尝试创建一个不会对填充值求和的堆叠条形图。 例如,假设我有一个解决方案会随着温度 (y) 的升高而改变颜色。 我想要一个条形 plot 显示颜色,因为它随着温度升高而上升 y 轴。 我大部分都成功了,但是 y 轴刻度不正确
样本数据:
x<- data.frame(color = c("red", "blue", "red", "orange"), temperature = c(1, 5, 10, 20), trial = c(1, 1, 1, 1))
x
color temperature trial
1 red 1 1
2 blue 5 1
3 red 10 1
4 orange 20 1
请注意,只有一个试验,所以只有一个酒吧。 另请注意,当温度达到 5 时,颜色会从红色变为蓝色,当温度达到 10 时,颜色会从蓝色变为红色。我希望条形图沿 y 轴以类似的方式更改 colors。 当我 plot 它时,y轴刻度线是错误的:
[![#Convert to factors for plotting
x$temperature<- as.factor(x$temperature)
x$color<- as.factor(x$color)][1]][1]
#plot
library(ggplot2)
ggplot(x, aes(x = trial, y = temperature, fill = color))+
geom_bar(position = "stack", stat = "identity")
请注意,在我的 output 图像中,y 轴刻度与数据不对齐(请注意,栏中的 colors 与 Z6A8064B5DF479455507D553C47C5 中的“颜色”值不对应。
将值转换为因子后,请注意数据的水平。
levels(x$temperature) #This is correct
[1] "1" "5" "10" "20"
levels(x$color) #This is not correct
#[1] "blue" "orange" "red"
您需要color
具有与它们出现的顺序相同的因子水平。 一个简单的方法是使用fct_inorder
。 您可以使用scale_fill_identity
为条形分配与color
列中相同的颜色。
library(tidyverse)
x %>%
mutate(across(c(color, temperature), ~fct_inorder(as.character(.)))) %>%
ggplot(aes(x = trial, y = temperature, fill = color))+
geom_bar(position = "stack", stat = "identity") +
scale_fill_identity()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.