序言: 我最近有这个线程
目标
复制这个情节
当前代码
library(tidyverse)
data <- data.frame(
labels = c("A","B","C","D","E","F","G","H"),
values = c(88, 61, 56, 77, 83, 63, 42, 60)
) %>%
mutate(
bar_color = case_when(
values < 62 ~ "#f2452e",
values < 85 ~ "#76c5d0",
values >= 85 ~ "#4b7d84",
)
)
ggplot(data, aes(x = labels, y = values)) +
geom_bar(aes(fill = bar_color),
stat = "identity", size = 1,
color = "gray20", width = 1,
alpha = 0.8) +
coord_polar(start = -(pi / 8)) +
scale_fill_identity() +
theme(
panel.grid.major.y = element_line(
linewidth = .8,
color = c("transparent", alpha("grey80", 0.5))
),
axis.title = element_blank(),
panel.background = element_blank(),
axis.ticks.y = element_blank(),
axis.text = element_blank(),
) +
geom_hline(yintercept = 96.5,
color = "grey90", size = 3) +
scale_y_continuous(breaks = seq(0, 95, 5)) +
geom_segment(aes(x = 1.5:8.5, y = 0, yend = 95),
inherit.aes = FALSE, color = alpha("grey20", 0.5)) +
geom_hline(yintercept = 94,
color = "grey20", size = 1) +
geom_label(aes(label = labels, y = 96), fill = "white", size = 6)
当前剧情:
问题
价值:
breaks
在 scale_y_continuous()
yintercept
在 geom_hline()
yend
中geom_segment()
;和y
在 geom_label()
全部都是硬编码的。当
data$values
变化时,尤其是在95以上(最大为100)时,这成为挑战。我需要帮助以确保问题 #1
到 #4
的值保持在 100
左右以覆盖 data$values
的所有可能值
将我的评论作为答案更加明确。
data$values
我也:
size
中将 linewidth
替换为 geom_hline
,因为它会引发弃用警告结果如下:
library(tidyverse)
data <- data.frame(
labels = c("A","B","C","D","E","F","G","H"),
values = c(88, 61, 56, 77, 83, 63, 42, 98)
) %>%
mutate(
bar_color = case_when(
values < 62 ~ "#f2452e",
values < 85 ~ "#76c5d0",
values >= 85 ~ "#4b7d84"))
ymax <- max(data$values)
p <- ggplot(data, aes(x = labels, y = values)) +
geom_bar(aes(fill = bar_color),
stat = "identity", size = 1,
color = "gray20", width = 1,
alpha = 0.8) +
coord_polar(start = -(pi / 8)) + scale_fill_identity() +
theme(
panel.grid.major.y = element_line(
linewidth = .8,
color = c("transparent", alpha("grey80", 0.5))),
axis.title = element_blank(),
panel.background = element_blank(),
axis.ticks.y = element_blank(),
axis.text = element_blank()) +
geom_hline(yintercept = ymax + 8.5,
color = "grey90", linewidth = 3) +
scale_y_continuous(breaks = seq(0, ymax + 7, 5)) +
geom_segment(aes(x = 1.5:8.5, y = 0, yend = ymax + 7),
inherit.aes = FALSE, color = alpha("grey20", 0.5)) +
geom_hline(yintercept = ymax + 6,
color = "grey20", linewidth = 1) +
geom_label(aes(label = labels, y = ymax + 8), fill = "white", size = 6)
print(p)
结果: