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 theformat
component of thescales
argument to specify the format of the axis labels:Lattice plots use the
pretty
function to help determine which axis labels to draw. Soshould 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 usingpretty
may deviate from the labels that actually get drawn.