Percent labels in scale_x_log10

2019-08-12 16:40发布

I am trying to graph a density plot in R using ggplot. The one nuance is that my x axis is logarithmic, using scale_x continuous. The following code works well:

ggplot(MELTCOMP,aes(x=value)) + geom_density(aes(fill=variable), alpha = 0.1) + 
                            scale_fill_manual(
                                              name = "Spend", 
                                              values = c("blue","red","green"), 
                                              labels = c("A","B","C")
                                              ) +
                            scale_x_log10(breaks = c(0.00001,0.0001,0.001,0.01,0.1,1,10,100),labels = percent) +
                            geom_vline(aes(xintercept = c(0.00001,0.0001,0.001,0.01,0.1,1,10,100)), color = "grey") + 
                            theme(axis.ticks = element_blank(), panel.background = element_blank(), panel.grid = element_blank(),
                                  axis.text.y = element_blank())

The problem is in how the x axis is displayed. When I use:

 scale_x_log10(breaks = c(0.00001,0.0001,0.001,0.01,0.1,1,10,100),label = percent)

from the scales package, my axis has labels:

0% - 0% - 0% - 0% - 10% - 100% - ...

Note the repeating "0%". I puzzled that this likely has to do with the scales percent function, given as

function (x) 
{
x <- round_any(x, precision(x)/100)
paste0(comma(x * 100), "%")
}

Trying to code my "own" function without the rounding:

NRPercent <- function(x) {
    paste0(comma(x * 100), "%")
}

scale_x_log10(breaks = c(0.00001,0.0001,0.001,0.01,0.1,1,10,100),label = NRpercent)

Gives:

0.001% - 0.010% - 0.100% - 1.000% - 10.000% - ...

Now I have a forced three decimals for every number, which often results in overlap. My desired would be:

0.001% - 0.01% - 0.1% - 1% - 10% - 100% - 1000% .....

but I cannot seem to replicate this. What is the right way to do this?

标签: r ggplot2
1条回答
兄弟一词,经得起流年.
2楼-- · 2019-08-12 17:27

Replace

paste0(comma(x * 100), "%")

with

paste0(sapply(x * 100, comma), "%")

The problem is that comma considers its whole input to determine a commonly usable number of significant digits – but this is precisely what you do not want. Unfortunately the function documentation fails to mention this. The relevant section can instead be found in format, which comma calls:

Numeric vectors are encoded with the minimum number of decimal places needed to display all the elements to at least the ‘digits’ significant digits.

查看更多
登录 后发表回答