【问题标题】:How to display geom_text as millions in ggplot2如何在ggplot2中将geom_text显示为数百万
【发布时间】:2021-01-29 19:30:31
【问题描述】:

通常要在 ggplot2 中以不同比例显示轴值,我们可以使用以下内容:

p + scale_y_continuous(labels = scales::unit_format(unit = "M", scale = 1e-6))

geom_text 标签如何做同样的事情?使用逗号,我们将执行以下操作

p + geom_text(aes(y = y_val, x = x_val, label = scales::comma(value))) 

是否有类似于逗号的函数用于数百万(例如:100M)?

【问题讨论】:

  • p + geom_text(aes(y = y_val, x = x_val, label = scales::unit_format(unit = "M", scale = 1e-6)(value))) 有效吗?如果您包含一个简单的reproducible example 以及可用于测试和验证可能的解决方案的示例输入,那么为您提供帮助会更容易。
  • 所以我实际上尝试了上面的方法,似乎额外的括号 (value) 不受欢迎。我希望有一个简单的comma 之类的函数,但是如果将上述方法应用于数据框并作为新变量调用,则上述方法确实有效。
  • “不欣赏”是什么意思 你的 data.frame 中有一个名为“value”的列吗?如果不是,那么具有要用作文本标签的值的列的名称是什么? value 就是你喜欢的任何列名。
  • unit_format 函数返回一个函数。您可以将其命名为 mill <- scales::unit_format(unit = "M", scale = 1e-6),然后调用 mill(c(1e6, 25e5)) 或在您的 aes 中使用它:label = mill(value),就像您使用任何其他函数一样。
  • 是的,我知道它是如何工作的,命名unit_format 的输出是要走的路

标签: r ggplot2 plot scale


【解决方案1】:

也许您可以在geom_text 中以类似的方式使用paste 来完成您的要求?

library(ggplot2)
library(dplyr)


example_data <- tibble(
  foo = c(1000000, 2000000, 3000000, 4000000, 5500000),
  bar = c(1000000, 2000000, 3000000, 4000000, 5500000)
)

ggplot(example_data, aes(x = foo, y = bar)) +
  geom_point() +
  geom_text(aes(label = paste(round(foo / 1e6, 1), "M")))

reprex package (v0.3.0) 于 2021-01-29 创建

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-10-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-10-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多