我正在尝试构建我的第一个斜率图,以在线指南为模型。
df1 <- dplyr::data_frame('tests' = c("2023","2024"),
'Pre-season Avg.' = c(42.35,51.38),
'Post-season Avg.' = c(90.4,86.56))
colnames(df1) <- c("tests", "Pre-season Avg.", "Post-season Avg.")
left_label <- paste(df1$'tests', df1$'Pre-season Avg.')
right_label <- paste(df1$'tests', df1$'Post-season Avg.')
df1$class <- ifelse((df1$'Post-season Avg.' - df1$'Pre-season Avg.') < 0, "red", "dodgerblue")
plot <- ggplot(df1) +
geom_segment(aes(x=1, xend=2, y="Pre-season Avg.", yend="Post-season Avg.", col=class), size=0.75,
show.legend=F) +
geom_vline(xintercept=1, linetype="dashed", size=0.1) +
geom_vline(xintercept=2, linetype="dashed", size=0.1) +
scale_color_manual(labels = c("Up","Down"),
values=c("red", "dodgerblue")) +
labs(x="", y="Scores by Average") +
xlim(0.5,2.5) + ylim(0, (1.1*(max(df1$'Pre-season Avg.', df1$'Post-season Avg.'))))
plot <- plot + geom_text(label=left_label, y=df1$'Pre-season Avg.', x=rep(1, NROW(
df1)), hjust=1.1, size=3.5)
plot <- plot + geom_text(label=right_label, y=df1$'Post-season Avg.', x=rep(2, NROW(
df1)), hjust=-0.1, size=3.5)
plot <- plot + geom_text(label="Pre-season", x=1, y=1.1*(max(df1$'Pre-season Avg.', df1$'Post-season Avg.')),
hjust=1.2, size=5)
plot <- plot + geom_text(label="Post-season", x=2, y=1.1*(max(df1$'Pre-season Avg.', df1$'Post-season Avg.')),
hjust=-0.1, size=5)
plot + theme(panel.background = element_blank(),
panel.grid = element_blank(),
axis.ticks = element_blank(),
axis.text.x = element_blank(),
panel.border = element_blank(),
plot.margin = unit(c(1,2,1,2), "cm"))
plot
和df1$'Pre-season Avg.'
都是,df1$'Pre-season Avg.'
但double
我收到了警告:
Error in `ylim()`:
! Discrete values supplied to continuous scale.
ℹ Example values: "Pre-season Avg." and "Pre-season Avg."
但我不明白为什么会收到警告,因为我(至少我认为)在连续尺度上使用连续值。我显然犯了一个错误,但我无法确定它是什么。
您定义
aes(y="Pre-season Avg.")
。这被解释为字符串"Pre-season Avg."
,并且字符串是离散的。要么使用更适合编程的变量名,然后使用例如aes(y = pre_season_avg)
或使用反引号,如aes(y=`Pre-season Avg.`)
总的来说,我会做很多不同的事情,以使情节更容易构建: