简体   繁体   中英

How can I make the y axis on a r plot display numbers in decimal format with commas?

I am running the following R code:

plot(datereal, casesimm8lock7,
type = "l", lwd = 1, col = "red", 
main = "a Sensitivity to time delays: 8 month immunity", 
xaxt = "n", xlab = "Month",
ylab = "Daily new cases", ylim = c(0,250000))

And I want the y-axis, which currently displays 50000 100000 150000 etc. to display 50,000 100,000 150,000 etc.

I am trying to use the scales package but haven't figured it out yet.

Start by making an empty plot with no y axis. Then plot the data.

Then plot the y axis with axis(2, ...) . In order to have the labels formatted like the question asks for, use help("formatC") .

# test data
datereal <- Sys.Date() - 10:0
casesimm8lock7 <- seq(0,250000, length.out = 11)

# the plot
plot(datereal, casesimm8lock7, type = "n", yaxt = "n")
lines(datereal, casesimm8lock7,
      lwd = 1, col = "red", 
      main = "a Sensitivity to time delays: 8 month immunity", 
      xaxt = "n", xlab = "Month",
      ylab = "Daily new cases", ylim = c(0,250000))
axis(2, at = seq(0, 250000, by = 50e3),
     labels = formatC(seq(0, 250000, by = 50e3), 
                      format = "d", big.mark = ","))

在此处输入图片说明

With package scales , it could be with either label_comma , like below, or label_number . Thse functions return a labeller function, to be applied to the vector of axis marks.

labeller <- scales::label_comma()

plot(datereal, casesimm8lock7, type = "n", yaxt = "n")
lines(datereal, casesimm8lock7,
      lwd = 1, col = "red", 
      main = "a Sensitivity to time delays: 8 month immunity", 
      xaxt = "n", xlab = "Month",
      ylab = "Daily new cases", ylim = c(0,250000))
axis(2, at = seq(0, 250000, by = 50e3),
     labels = labeller(seq(0, 250000, by = 50e3)))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM