【问题标题】:How to tailor the x-axis of a ggplot to include dates如何定制 ggplot 的 x 轴以包含日期
【发布时间】:2021-01-26 01:38:12
【问题描述】:

如何在 ggplot 的 x 轴上插入日期,如下所示:

感谢 SO 的帮助,我设法在 R 的基本绘图功能中定制了 x 轴:

但是,用于生成第二个图的关键两行代码:

at1 <- seq(min(ccw$date), max(ccw$date), by=1+.02*length(ccw$date))
axis.Date(1, at=at1, format="%b %d", las=2, cex.axis=0.7)

似乎不太容易适应 ggplot,而我只被当天的数字所困。顺便说一句,如果您要生成带有解决我的问题的修复程序的图,并且可以找到一种方法使总体上的置信带更宽,我将不胜感激。

这是生成两个图的完整代码:

install.packages('RCurl')
install.packages('zoo')
suppressPackageStartupMessages({
    require(repr) # Enables resizing of the plots.
    require(RCurl)
    require(foreign)
    require(tidyverse) # To tip the df from long row of dates to cols (pivot_longer())
    require(zoo) # Rolling average
    require(RColorBrewer)
})

x = getURL("https://raw.githubusercontent.com/CSSEGISandData/COVID-19/master/csse_covid_19_data/csse_covid_19_time_series/time_series_covid19_confirmed_global.csv")
corona <- read.csv(textConnection(x))

corona = (read_csv(x)
          %>% pivot_longer(cols = -c(`Province/State`, `Country/Region`, Lat, Long),
                           names_to = "date",
                           values_to = "cases")
          %>% select(`Province/State`,`Country/Region`, date, cases)
          %>% mutate(date=as.Date(date,format="%m/%d/%y"))
          %>% drop_na(cases)
          %>% rename(country="Country/Region", provinces="Province/State")
)
 
cc <- (corona
       %>% filter(country %in% c("Italy", "Spain","US", "Norway", "Denmark", "Sweden","Korea, South", "Brazil","India", "United Kingdom", "Mexico"))
)
 
ccw <- (cc
        %>% pivot_wider(names_from="country",values_from="cases")
        %>% filter(Italy>5)
)

x = getURL("https://raw.githubusercontent.com/CSSEGISandData/COVID-19/master/csse_covid_19_data/csse_covid_19_time_series/time_series_covid19_confirmed_global.csv")
corona <- read.csv(textConnection(x))

corona = (read_csv(x)
          %>% pivot_longer(cols = -c(`Province/State`, `Country/Region`, Lat, Long),
                           names_to = "date",
                           values_to = "cases")
          %>% select(`Province/State`,`Country/Region`, date, cases)
          %>% mutate(date=as.Date(date,format="%m/%d/%y"))
          %>% drop_na(cases)
          %>% rename(country="Country/Region", provinces="Province/State")
)
 
cc <- (corona
       %>% filter(country %in% c("Italy", "Spain","US", "Norway", "Denmark", "Sweden","Korea, South", "Brazil","India", "United Kingdom", "Mexico"))
)
 
ccw <- (cc
        %>% pivot_wider(names_from="country",values_from="cases")
        %>% filter(Italy>5)
)


options(repr.plot.width=13, repr.plot.height=8)

ccw$first.der <- c(NA, diff(ccw$US))  ## better add an NA and integrate in data frame
ccw$day <- seq_along(ccw$date)

first.der <- diff(ccw$US, lag = 1, differences = 1)


k=7
MAV <- rollmean(first.der,k)

fit8 <- lm(first.der ~ poly(day, 8, raw=TRUE), ccw[-1, ]) # OCTIC!

par(mar=c(5,5,3,2))
with(ccw, plot(day, first.der, 
      main="Daily COVID-19 Cases in the US", cex.main=2,
      axes=FALSE,
      xlab='', 
      ylab='',
      las = 2,
      col=rgb(0.4,0.4,0.8,0.6), pch = 16, cex = .6))

abline(h=0)
abline(h=ccw$first.der[length(ccw$day)], col='red', lty=2)

tck <- seq(min(ccw$day), max(ccw$day), by=10)
axis(1, tck, labels=FALSE)

at2 <- seq(min(first.der),max(first.der)+150000, 0.10 * max(first.der))
axis(side=2, at2, 
     las=2, cex.axis=1, labels = formatC(at2, big.mark = ",", format = "d"))

mtext(strftime(ccw$date[tck], "%b %d"), 1, 1, at=tck, las=2)

lines(fit8$fitted.values, col=alpha('blue',.8), lwd=2)
points(ccw$day, ccw$first.der, main="US covid-19", pch=16, col=rgb(0.8,0.2,0.1,0.6))
points(tail(ccw$day,1), last(ccw$first.der), main="US covid-19", pch=19, cex=1.2, col='red')


ggplot(ccw, aes(x = day, y = first.der)) + geom_point() +
  geom_vline(xintercept = 0, color = "red")  + 
  geom_point(mapping = aes(x = ccw$day, y = ccw$first.der), color = "blue") +
  geom_smooth(method = "lm", formula = y ~ poly(x, 8))

【问题讨论】:

    标签: r ggplot2 plot


    【解决方案1】:

    在 x 轴上保留 Date 列,以便您可以使用 scale_x_date 根据您的选择包含标签和中断。

    library(ggplot2)
    
    ggplot(ccw, aes(x = date, y = first.der)) + 
      geom_point() +
      geom_vline(xintercept = 0, color = "red")  + 
      geom_point(color = "blue") +
      geom_smooth(method = "lm", formula = y ~ poly(x, 8)) + 
      scale_x_date(date_labels = '%b %d', breaks = '2 week') + 
      theme(axis.text.x = element_text(angle = 90, vjust = 0.5, hjust=1)) + 
      scale_y_continuous(labels = scales::comma)
    

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-02-05
    • 2021-04-08
    • 1970-01-01
    • 2023-03-30
    • 2023-03-20
    • 2020-03-19
    相关资源
    最近更新 更多