如何将 y 轴更改为美元格式并避免使用科学计数法?

Gab*_*ain 2 r ggplot2 dplyr tidyverse

我正在尝试学习如何将美元格式分配给 Y 轴并避免使用科学记数法。我有options(scipen = 999)

  ggplot(diamonds, aes(y = cut_width(price, 2000, boundary = 0), x = carat)) +
    geom_boxplot(varwidth = TRUE) +
    scale_y_continuous(dollar_format()) +
    xlab("Carat") +
    ylab("Price")
Run Code Online (Sandbox Code Playgroud)

以上返回:Error: Discrete value supplied to continuous scale. 我尝试通过删除cut_width和简化情节来修改代码,但无济于事。我缺少什么?谢谢你!

Ian*_*ell 5

这不起作用的原因是因为cut_width返回一个因子而不是一个数字。因此scales::dollar_format无法工作,因为它不是一个数字。此外,您不能使用_scale_continuousfor 因子。

这是一种使用fromdig.lab =重新格式化 y 轴标签的方法。str_replace_allstringr

我们需要dig.lab =阻止科学记数法。看help(cut_width)

如您所知,我们可以要求ggplot使用函数转换 y 轴标签,因此我们将利用这一点并定义一个匿名函数来在字符串中进行一些替换。使用stringr::str_replace_all,我们可以提供一个命名的向量pattern = replacement对。因此,我们将(or替换[$,- $,并且]什么也不替换。我们需要使用 转义特殊的正则表达式字符\\

library(ggplot2)
library(stringr)
ggplot(diamonds, aes(y = as.factor(cut_width(price, 2000, boundary = 0, dig.lab=10)), x = carat)) +
    geom_boxplot(varwidth = TRUE) +
    scale_y_discrete(labels = function(x) str_replace_all(x, regex(c("[\\(\\[]" = "$", "," = " - $", "\\]" = "")))) +
    xlab("Carat") +
    ylab("Price")
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述