【问题标题】:ggplot negative sign in continues color scale does not align in center of text连续色标中的ggplot负号未在文本中心对齐
【发布时间】:2023-01-20 01:24:47
【问题描述】:

所以我用ggplot2 做了一个图,为了尽可能多地删除空白,我删除了图例键和图例文本之间的间距。令我惊讶的是,- 符号没有在文本的中心对齐,看起来文本与颜色图例上的刻度没有对齐。

是否有任何技巧可以正确对齐 - 标志?它在我看来非常难看,因为它与 - 符号几乎对齐,. 用于指示小数。

编辑:值得注意的是,我正在寻找一种无需每次都手动设置中断/标签/值的程序化解决方案。

MWE:

library(tibble)
library(ggplot2)
#> Warning: package 'ggplot2' was built under R version 4.2.2
set.seed(1)
tibble(
  y = 1:10,
  x = 1:10,
  c = -runif(10)
) %>% 
  ggplot(aes(x, y, color = c)) +
  geom_point() +
  theme(
    legend.position = c(.5, .5),
    legend.text = element_text(size = 12),
    legend.spacing.x = unit(.1, 'pt')
  )

创建于 2023-01-19 reprex v2.0.2

【问题讨论】:

  • 这很可能与您使用的字体有关,而不是 ggplot 本身。在文字处理器中尝试使用相同字体(默认 ggplot 使用取决于您的系统)中的相似文本,并查看垂直对齐方式是否与字符的基线大致相同。您可以尝试找到一种标志更居中的字体

标签: r ggplot2


【解决方案1】:

您可以使用算术减号 (unicode 2212) 替换默认减号。这可以通过传递给 scale_color_continuouslabels 参数的一个小 lambda 函数来完成

library(tibble)
library(ggplot2)

set.seed(1)
tibble(
  y = 1:10,
  x = 1:10,
  c = -runif(10)
) %>% 
  ggplot(aes(x, y, color = c)) +
  geom_point() +
  scale_color_continuous(labels = ~paste(ifelse(sign(.x) == -1, "u2212", ""),
                                         sprintf("%2.2f", abs(.x)))) +
  theme(
    legend.position = c(.5, .5),
    legend.text = element_text(size = 12),
    legend.spacing.x = unit(.1, 'pt')
  )

创建于 2023-01-19 reprex v2.0.2

【讨论】:

  • 谢谢!这看起来好多了。
猜你喜欢
  • 2013-02-23
  • 1970-01-01
  • 2016-09-21
  • 2022-11-11
  • 2020-08-23
  • 2021-12-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多