문제

I'm using lattice to make xyplots of weekly car sales by color. There are 108 weeks of data currently and I'd like to update this data weekly, so next week there will be 109 weeks of data, etc.

I'm having an issue formatting the x (date) axis appropriately. Going off what I read in other SO threads about this (e.g. this) I came up with the code below. The dates are now in my desired format of %d-%b, but now I have every single week showing (all 108 of them.)

The desired behavior is to both specify the format of the date (%d-%b) and also automatically fit the axis to the chart, letting R determine how many dates to show at once based on the size of the chart and how many weeks of data. (I understand I could filter the labels and specify how many I want to appear, but this is not the desired behavior.)

Here's my code:

library(lattice)

salesData <- read.csv("http://s3.amazonaws.com/rk-misc/samples/sales.csv")

# convert to date format
salesData$week <- as.POSIXct(strptime(salesData$week,"%Y-%m-%d"))

# plot
xyplot(sales ~ week | carColor, data=salesData[order(salesData$week),], 
  type="l",
  scales = list(
    x = list(
      at = salesData$week,
      labels = format(salesData$week, "%d-%b")
    )
  ),
  xlab = "Date",
  ylab = "Sales"
)

Thanks!

도움이 되었습니까?

해결책

Since you convert your x-axis data to the POSIXct class, you can use the format component of the scales argument to specify the format of the axis labels:

xyplot(sales ~ week | carColor, data=salesData[order(salesData$week),], 
  type="l",
  scales = list(
    x = list(
      format = "%d-%b" # Here's where you choose the format
    )
  ),
  xlab = "Date",
  ylab = "Sales"
)

Lattice plots use the pretty function to help determine which axis labels to draw. So

format(pretty(salesData$week), "%d-%b")

should in most cases return the labels that get drawn. Lattice (more specifically grid) graphics also check for potential overlap of axis labels. In cases where the labels would potentially overlap, simply using pretty may deviate from the labels that actually get drawn.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top