[英]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.