首页 > 解决方案 > ggplot2。如何根据背景更改数据标签的颜色(geom_segment)

问题描述

我在下面制作了一个不错的李克特式图。我在片段上贴了标签以提高清晰度。但是,我希望标签在深色背景上为白色,在浅色背景上为黑色。我怎样才能做到这一点?

李克特式情节

我尝试为我想要为其拥有黑色数据标签的所有变量设置额外的虚拟变量,而为我想要为其拥有白色数据标签的所有变量设置额外的虚拟变量。然后我将参数添加color = dummygeom_text_repel. 尽管标签具有正确的颜色,但段会改变颜色并导致不良结果。

另一个(错误的)Likert-style_plot

我的代码如下:

color_palette = c("#525199", "#9393C6", "#A8A8A8","#FFA166", 
                  "#FF6200", "#FFFFFF", "#000000")

title <- "If you were to buy a car, would you choose...?"
subtitle <- "Subtitle"

# basic plot

p <- dane_3long %>% 
  ggplot() +
  geom_segment(aes(x = pytanie, y = start, xend = pytanie, 
                   yend = start + value, colour = variable), 
               size = 8) +
  scale_color_manual("", 
                     labels = c("1 - definitely no", "2", "3", "4", "5 - definitely yes"), 
                     values = ING_Likert_palette, guide = "legend") +
  coord_flip() +
  geom_hline(yintercept = 0, color =c("#A8A8A8"))

# Below I create labels 

p <- p + geom_text(aes(label = scales::percent(round((value), digits = 2)), 
                       colour = dummy, x = pytanie, y = (start + value)-value/2), 
                   size = 3, family = "ING Me") +
  theme_classic() +
  scale_y_continuous(breaks = seq(- 75, 75, 25), limits=c(- 0.73, 0.7))

# Below is styling of the plot

p <- p + labs(title = title, 
              subtitle = subtitle, 
              caption = "Źródło: Barometr finansowy ING", 
              y= " Percent", x= "") +
  theme(plot.title = element_text(face = "bold", size = 12),
        plot.subtitle = element_text(size = 9),
        plot.caption = element_text(size = 7, face = "italic"),
        legend.position = "right",
        legend.text = element_text(family = "ING Me",
                                   size = 8,
                                   color = grey(.3)),
        axis.title.x = element_blank(),
        axis.title.y = element_blank(),
        axis.line = element_blank(),
        axis.ticks = element_blank(),
        axis.text.x = element_blank(),
        text = element_text(family = "ING Me",
                            size = 14,
                            color = grey(.3))); p

标签: rggplot2colorslikert

解决方案


推荐阅读