我有一个堆积的条形图,标有geom_text
。为了提高标签的可见度,我想根据“黑暗”将标签颜色设置为白色或黑色。它们的背景,即条形的填充颜色。因此,较暗的条纹应该有白色标签,较亮的条纹应该有黑色标签。
我开始使用问题Showing data values on stacked bar chart in ggplot2中的代码,问题Is there a is light or is dark color function in R?的答案。最重要的是,我想在白色'白色'中显示数据值的标签。或者'黑色'取决于堆叠的条形填充颜色是分别是暗还是暗。
我做了两次尝试。第一个是使用aes(colour=...)
函数的geom_text
,但这个失败了......为什么?
第二次尝试使用函数scale_colour_manual
。但是这里堆叠的条形线条也是“彩色的”#34;使用黑色或白色切换设置。
library(ggplot2)
library(RColorBrewer)
Year <- c(rep(c("2006-07", "2007-08", "2008-09", "2009-10"), each = 4))
Category <- c(rep(c("A", "B", "C", "D"), times = 4))
Frequency <- c(168, 259, 226, 340, 216, 431, 319, 368, 423, 645, 234, 685, 166, 467, 274, 251)
Data <- data.frame(Year, Category, Frequency)
isDark <- function(color) {
(sum(grDevices::col2rgb(color) *c(299, 587,114))/1000 < 123)
}
## control the color assignments
paletteName <- 'Set1' # 'Dark2'
colorsPerCat <- brewer.pal(name=paletteName,n=4)
names(colorsPerCat) <- c("A", "B", "C", "D")
## First attempt
Data$LabelColor <- as.character(as.vector(sapply(unlist(colorsPerCat)[Data$Category], function(color) { if (isDark(color)) 'white' else 'black' })))
Data
p <- ggplot(Data, aes(x = Year, y = Frequency, fill = Category, label = Frequency)) +
geom_bar(stat = "identity") +
geom_text(aes(colour=LabelColor), size = 3, position = position_stack(vjust = 0.5)) +
scale_fill_manual(values = colorsPerCat)
p
## Second attempt
labelColoursPerCat <- sapply(as.vector(colorsPerCat), function(color) { if (isDark(color)) 'white' else 'black' })
names(labelColoursPerCat) <- c("A", "B", "C", "D")
p <- ggplot(Data, aes(x = Year, y = Frequency, fill = Category, label = Frequency, colour = Category)) +
geom_bar(stat = "identity") +
geom_text(size = 3, position = position_stack(vjust = 0.5)) +
scale_fill_manual(values = colorsPerCat) +
scale_colour_manual(values = labelColoursPerCat)
p
答案 0 :(得分:2)
通过玩geom_bar
颜色或尺寸来解决此问题的两种方法:
Data$LabelColor <- as.factor(Data$LabelColor)
p <- ggplot(Data, aes(x = Year, y = Frequency, fill = Category, label = Frequency, colour = LabelColor)) +
geom_bar(stat = "identity", color = "black") +
geom_text(size = 3, position = position_stack(vjust = 0.5)) +
scale_fill_manual(values = colorsPerCat) +
scale_colour_manual(values = levels(Data$LabelColor)) +
guides(colour = FALSE)
Data$LabelColor <- as.factor(Data$LabelColor)
p <- ggplot(Data, aes(x = Year, y = Frequency, fill = Category, label = Frequency, colour=LabelColor)) +
geom_bar(stat = "identity", size = 0) +
geom_text(size = 3, position = position_stack(vjust = 0.5)) +
scale_colour_manual(values = levels(Data$LabelColor)) +
scale_fill_manual(values = colorsPerCat) +
guides(colour = FALSE)