【发布时间】:2020-03-22 23:02:54
【问题描述】:
根据发布在其他地方 (ggplot2: text color based on background contrast) 的解决方案,我创建了一个简单的条形图,其标签应根据条形的颜色显示为白色或黑色(即黑色条的白色文本)。
首先,我不确定代码是否按预期工作,因为白色文本被用于标记浅色条。其次,图例包含一些我用来分配颜色的代码。
您对解决这两个问题有什么建议吗?我已附上图表的图像以供参考。
# Create a table of the proportions for use when creating the plot.
plotdata <- treatment_dataset %>%
group_by(STAGE, TREATMENT_GROUP) %>%
summarize(n = n()) %>%
mutate(pct = n/sum(n),
percentages = scales::percent(pct))
plotdata
# Plot the data from the table above
ggplot(plotdata,
aes(x = STAGE,
y = pct,
fill = TREATMENT_GROUP)) +
geom_bar(stat = "identity",
position = "fill") +
labs(y = "Proportion of tumours",
x = "Tumour stage at diagnosis",
fill = "Treatment group"
) +
scale_y_continuous(labels = scales::percent) -> treatment_by_stage
# Apply PHE formatting.
treatment_by_stage + theme_phe("phe") +
scale_fill_phe(name = "Treatment group",
theme = "phe") +
geom_text(aes(label = ifelse(pct < 0.05, NA, percentages), color = plotdata$pct > 0.01),
size = 3,
position = position_stack(vjust = 0.5)
) +
scale_color_manual(values = c("black", "white"))
【问题讨论】:
-
如果您认为您所指的问题对您没有帮助 - 请在问题中解释您为什么这么认为以及您尝试了什么
-
嘿,如果文本颜色以填充颜色为条件,那么 pct