我在為 ggplot2 直方圖著色時遇到問題。
R-垃圾
ggplot(Hospital, aes(x=BodyTemperature))
geom_histogram(aes(fill = factor(BodyTemperature)))
scale_x_continuous(breaks = seq(0, 100, by = 10))
ylab("prevalence")
xlab("BodyTemperature")
ggtitle("Temperature vs. prevalence")
所以直方圖應該繪制資訊(x 軸),即溫度越高,情況越差。例如,36°C 的“溫度”應該是綠色,38°C 黃色,40° 紅色 - 在 x 軸上從左到右。Y 軸應在醫院的患者資料中提供這些溫度出現的頻率。資料“BodyTemperature”是 200 多個資料的串列,例如:“35.3”或“37.4”等。
如何修復這個塊以提供顏色變化?對于我已經寫過這個 r-junk positiv 的非 ggplot 版本:
```{r, fig.width=8}
color1 <- rep(brewer.pal(1, "Greens"))
color2 <- rep("#57c4fa", 0)
color3 <- brewer.pal(8, "Reds")
hist(Hospital$BodyTemperature[-357],
breaks = seq(from = 0, to = 100, by = 10),
main = "Temperature vs. prevalence",
ylab = "prevalence",
xlab = "Temperature",
col = c(color1, color2, color3))
```
uj5u.com熱心網友回復:
關鍵是確保用于填充比例的 bin 間隔與用于 x 軸的 bin 間隔相匹配。您可以通過將binwidth引數設定為 來做到這一點geom_histogram(),并使用ggplot2::cut_width()來打破BodyTemperature填充比例的相同箱:
set.seed(13)
library(ggplot2)
# example data
Hospital <- data.frame(BodyTemperature = 36.5 rchisq(100, 2))
ggplot(Hospital, aes(BodyTemperature))
geom_histogram(
aes(fill = cut_width(BodyTemperature, width = 1)),
binwidth = 1,
show.legend = FALSE
)
scale_fill_brewer(palette = "RdYlGn", direction = -1)
labs(
title = "Temperature vs. Prevalence",
x = "Body Temperature (°C)",
y = "Prevalence"
)
theme_minimal()

使用reprex v2.0.2創建于 2022-10-24
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/523484.html
上一篇:嘗試在{ggplot}中使用geom_rug時check_aesthetics出錯
下一篇:使用兩個不同的調色板顯示圖例
