[英]R ggplot reversing one axis of a plot when there is more than one plot in the graph without affecting other plots
[英]R: ggplot: two plots in one dataframe: color one plot only when it is less than the other plot
我有来自 plot 上的单个 dataframe 的两个 geom_point 图。 我想要的是仅在 Y 轴上 plot 2 低于 plot 1 时为 label 着色。 所以如果它在上面,plot2 将是灰色/黑色,当它在下面时,它将被 dataframe 中的某一列标记
df <- setNames(data.frame(c("2022-07-29 00:00:00","2022-07-29 00:00:05",
"2022-07-29 00:05:00","2022-07-29 00:05:05",
"2022-07-29 00:10:00","2022-07-29 00:15:00",
"2022-07-29 00:20:00","2022-07-29 00:20:05"),
c(1,2,3,4,5,6,7,8),
c(0.8,2.1,2.5,4.1,5,6.1,6.9,8.1),
c("a","a","b","b","b","b","b","c")),
c("timeStamp", "value1", "value2", "text"))
所以我能想出的最接近的图表是
ggplot(df) +
geom_point(aes(timeStamp,value1))+
geom_point(aes(timeStamp, value2, color=value2>value1)) +
scale_color_manual(name="callout", values = setNames(c('green','red'), c(T,F)))
这个 plot 几乎正是我所需要的,但我希望第一个 plot 下方的红线使用 label 的文本列。 如果我将上面的 setNames 更改为 c('green', text),我认为它应该可以工作,但不能也无法找出正确的前进方向。 谢谢
这是我对你想要什么的解释。 关键线是
callout <- factor(ifelse(df$value2 > df$value1, NA, df$text))
如果 value2 小于 value1,它将为文本列设置颜色。
library(ggplot2)
df <-
setNames(data.frame(
as.POSIXct(
c(
"2022-07-29 00:00:00",
"2022-07-29 00:00:05",
"2022-07-29 00:05:00",
"2022-07-29 00:05:05",
"2022-07-29 00:10:00",
"2022-07-29 00:15:00",
"2022-07-29 00:20:00",
"2022-07-29 00:20:05"
)),
c(1, 2, 3, 4, 5, 6, 7, 8),
c(0.8, 2.1, 2.5, 4.1, 5, 6.1, 6.9, 8.1),
c("a", "a", "b", "b", "b", "b", "b", "c")
),
c("timeStamp", "value1", "value2", "text"))
# this works out the colours
callout <- factor(ifelse(df$value2 > df$value1, NA, df$text))
gg2 <-
ggplot(df) +
geom_point(aes(timeStamp,value1), col='grey50', size=3) +
geom_point(aes(timeStamp, value2, color = callout), size=3)
gg2
我还添加了as.POSIXct()
调用,使 x 轴更整洁。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.