Home > OS >  Decimal digits in `Slope Graph` with `ggplot2`
Decimal digits in `Slope Graph` with `ggplot2`

Time:01-11

Following a former question I opened few weeks ago: Graphical output

Below the whole code:

library(dplyr)
library(ggplot2)
#options(digits=3)


theme_set(theme_classic())


#### Data
df <- structure(list(group = c("Ups", "Ups", "Ups", "Ups", "Ups"), 
  yshift = c(0, 0, 0, 0, 0), x = structure(1:5, .Label = c("1 day", 
  "2 days", "3 days", "5 days", "7 days"), class = "factor"), 
  y = c(0.108, 0.8, 0.94, 1.511, 1.905), ypos = c(0.10754145, 
  0.8, 0.94, 1.5111111, 1.90544651164516)), row.names = c(1L, 
  3L, 5L, 7L, 9L), class = "data.frame")    


# Define functions. Source: https://github.com/jkeirstead/r-slopegraph

plot_slopegraph <- function(df) {
    ylabs <- subset(df, x==head(x,1))$group
    yvals <- subset(df, x==head(x,1))$ypos
    fontSize <- 3
    gg <- ggplot(df,aes(x=x,y=ypos))  
        geom_line(aes(group=group),colour="grey80")  
        geom_point(colour="white",size=8)  
        geom_text(aes(label=y), size=fontSize, family="American Typewriter")  
        scale_y_continuous(name="", breaks=yvals, labels=ylabs)
    return(gg)
}    

    
## Plot
plot_slopegraph(df)   labs(title="Monomer content after days of heating")

I am making any mistake or missing something? Is there any other way to force 0 digits?

Thank you in advance for every eventual reply or comment.

CodePudding user response:

I like the scales package functions for things like this (though you could certainly use formatC or sprintf instead).

I've modified plot_slopegraph to use label=scales::label_number(accuracy = 0.001)(y)) in the geom_text():

plot_slopegraph <- function(df) {
    ylabs <- subset(df, x==head(x,1))$group
    yvals <- subset(df, x==head(x,1))$ypos
    fontSize <- 3
    gg <- ggplot(df,aes(x=x,y=ypos))  
        geom_line(aes(group=group),colour="grey80")  
        geom_point(colour="white",size=8)  
        geom_text(aes(label=scales::label_number(accuracy = 0.001)(y)), size=fontSize, family="American Typewriter")  
        scale_y_continuous(name="", breaks=yvals, labels=ylabs)
    return(gg)
}    
plot_slopegraph(df)

enter image description here

  •  Tags:  
  • Related