【发布时间】:2020-10-05 04:20:00
【问题描述】:
我在 ggplot 中有一个条形图,我想在其中为条形图上色,它们落在哪个范围内。我已经绘制了 hlines 以显示我想要颜色变化的位置:0.4、0.5、0.6。我能找到的所有东西都会根据渐变进行着色。但是,我希望超过 0.6 的每个条都是相同的绿色,低于 0.4 的每个条都是相同的红色,等等。
attach(screen2D)
screen2D[order(screen2D[,2]),]
library(ggplot2)
ggplot(screen2D) +
geom_bar(aes(x = reorder(Target, -Median),
y = Median),
stat = "identity",
fill = "skyblue") +
geom_errorbar(aes(x = reorder(Target,
- Median),
ymin = Q1, ymax = Q3),
width = 0.25, colour = "black",
alpha = 0.9, size = 0.2) +
ggtitle("Title") +
xlab("X Label") +
ylab("Y Label") +
theme(plot.title = element_text(hjust = 0.5),
axis.text.x = element_text(angle = 90,
hjust = 1,
vjust = 0.25)) +
scale_y_continuous(expand = c(0,0),
limits = c(0,1)) +
geom_hline(yintercept = 0.40, linetype = "dashed",
color = "red") +
geom_hline(yintercept = 0.50, linetype = "dashed",
color = "red") +
geom_hline(yintercept = 0.60, linetype = "dashed",
color = "red")
Plot Output
geom_bar 中的 fill 参数要求长度为 1 或与数据集的长度相同,在本例中为 102。有解决办法吗?
我认为scale_fill_manual 对breaks 参数很有用,但这似乎只指定了一个单独的变量。
+ scale_fill_manual(
values = c("red", "yellow", "orange", "green"),
breaks = c(Median<0.4, 0.4<Median<0.5,
0.5<Median<0.6, 0.6<Median))
有没有办法实现这一点,而无需手动将数据集分成 4 个并单独添加在一起?
【问题讨论】:
-
我的建议是添加一个具有您描述的颜色逻辑的列,并将该列传递给
fill审美。 -
@ValeriVoev 感谢您的帮助。完美运行。