我有一个数据集,在轴上显示太多标签。当我把它显示为几个月时,它太拥挤了。我希望将标签更改为年,但保持线不变。
以下是一些示例代码,用于解释我正在尝试的内容。
library (ggplot2)
library (dplyr)
library (tidyr)
# create data
a = paste("m_",1:36,sep = "") # lables for 36 months of data
b = paste("c",1:6,sep = "")
mydata = data.frame(matrix(rnorm(36),6,36))
names(mydata) = a
mydata$cust = b
mydata = mydata[,c(ncol(mydata),1:(ncol(mydata)-1))] #move "cust" to 1st column
# plot data
p_data = mydata %>% gather(period,Qty,-cust)
p_data[, 2] <- factor(p_data[, 2], levels = unique(p_data[, 2])) # from Stackoverflow (thanks!)
pl=(ggplot(data=p_data,aes(x=period,y=Qty,group=cust,colour=cust)) +
geom_line(size=.4))
# print plot
pl
答案 0 :(得分:2)
#Look at `?scale_x_discrete`, for example:
#Make x axis breaks and labels
xbrks <- c('m_1', 'm_13', 'm_25', 'm_36')
xlabs <- paste('Year', 1:length(xbrks))
# plot data
p_data = mydata %>% gather(period,Qty,-cust)
p_data[, 2] <- factor(p_data[, 2], levels = unique(p_data[, 2])) # from Stackoverflow (thanks!)
pl=(ggplot(data=p_data,aes(x=period, y=Qty,group=cust,colour=cust)) +
geom_line(size=.4)) + scale_x_discrete(breaks=xbrks, labels=xlabs)
# print plot
pl