r - 如何正确使用 scale_x_date
问题描述
我是 R 的新用户,希望你能帮助我。
setwd("C:/Users/USER/Desktop/Jorge")
agua <- read_excel("agua.xlsx")
pbi <- read_excel("PBIagro.xlsx")
str(agua);
names(agua)[2] <- "Variación";
agua[,1] <- as.Date(agua$Trimestre)
lagpbi <- lag(pbi$PBIAgropecuario, k=1)
pbi[,3]<- lagpbi; pbi <- pbi[-c(1),];
names(pbi)[3] <- "PBIlag"
growth <- ((pbi$PBIAgropecuario-pbi$PBIlag)/pbi$PBIlag)*100
Anual_growth <- data.frame(growth); Anual_growth[,2] <- pbi$Año; names(Anual_growth)[2] <- "Año"
# Plot
Agro <- ggplot(Anual_growth, aes(x=Año, y=growth)) +
geom_line(color="steelblue") +
geom_point() +
geom_text(aes(label = round(Anual_growth$growth, 1)),
vjust = "inward", hjust = "inward", size=2.5, show.legend = FALSE) +
xlab("") +
theme_ipsum() +
theme(axis.text.x=element_text(angle=60, hjust=1)) +
ylim(-9.9,13.4) +
theme(panel.grid.major = element_blank(), panel.grid.minor = element_blank(),
axis.line.x = element_blank(), plot.margin = unit(c(1,1,0.5,1),"cm"),
axis.line.y = element_blank(), axis.text.x=element_text(face = "bold", size=8,
angle=1,hjust=0.95,vjust=0.2),
axis.text.y = element_blank(), axis.title.y=element_blank())+
scale_x_continuous("Año", labels = as.character(Anual_growth$Año), breaks = Anual_growth$Año)
print(Agro)
问题是它显示了所有年份,但我只想要成对年份(在 X 轴上)或步长等于 2 的年份。我希望你能真正帮助我。谢谢你。请注意,X 轴变量是一个数字字符串。
解决方案
您可以
scale_x_date(date_breaks = "2 years", date_labels = "%Y")
在 ggplot 中添加类似的内容。
这就是我的数据的样子,因为你还没有发布你的数据。我date
在 x 轴上绘制一个类型。
1.
ggplot(mydata) +
aes(x = date, y = number, color = somevar) +
geom_line()
ggplot(mydata) + aes(x = date, y = number, color = somevar) + geom_line() + scale_x_date(date_breaks = "1 year", date_labels = "%Y")
3.
ggplot(mydata) +
aes(x = date, y = number, color = somevar) +
geom_line() +
scale_x_date(date_breaks = "2 years", date_labels = "%Y")
推荐阅读
- c# - 我可以将 mdb vue (Material Design Vue) 与 Bootstrap Vue 一起使用吗?有哪些风险?
- django - Django 使用 .set 添加多个 m2m 相关模型记录工作正常,但如何添加除 ids 之外的其他模型字段?
- python - 如何通过 django 和请求获得 http 长连接?
- python - 如何通过python使用psutil获取cpu_persent
- android - 谷歌助手与 Android 应用程序的对话
- javascript - 如何使用 redux saga 从 redux 商店获取商品:已解决
- sql - 检查约束-1
- python-requests - 如何将表单数据中的国家/地区代码发布到 URL 以获取预期的 WebData?
- php - 将图像上传到 GoDaddy PHP 表单
- reactjs - 错误:使用 react-hooks 时超出最大更新深度